It is very common to check that arguments passed to a method meet certain criteria and if they do not to signal this back with an exception such as ArgumentOutOfRangeException or ArgumentNullException.
For these exceptions to be useful they need to indicate which parameter the argument is not valid for and so take a paramName string in the constructor. This is error-prone and when parameters are renamed refactoring tools typically ignore strings that contain the same value.
nameof allows you to capture the name of a parameter, variable, type or member as a string at compile time to remove this dependency.
Code
csharp
IEnumerable<Customer> SearchCustomers(string postCode)
{
if (postCode == null)
throw new ArgumentNullException(nameof(postCode));
return customers.Where(c => c.PostCode == postCode);
}csharp
IEnumerable<Customer> SearchCustomers(string postCode)
{
if (postCode == null)
throw new ArgumentNullException("postCode");
return customers.Where(c => c.PostCode == postCode);
}Notes
- Only the final identifier is returned, so
nameof(System.Console.WriteLine)is"WriteLine" - CallerArgumentExpression C# 10.0 allows the name to be captured automatically
- .NET 6 and later use it to provide static helpers like
ArgumentNullException.ThrowIfNull(postCode)
- .NET 6 and later use it to provide static helpers like
- Extended nameof scope C# 11.0 and Unbound generic types and nameof C# 14.0 extend where it can be used