Skip to content

nameof operator C# 6.0correctness

Capture the name of a variable or method at compile time.

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 message 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 parameterName string in the constructor. This is error-prone and when parameter names are refactored development tools typically ignore strings that contain the same value.

nameof allows you to capture the name of a parameter to compile-time to reduce this dependency.

Code

C#
IEnumerable<Customer> SearchCustomers(string postCode)
{
    if (postCode == null)
        throw new ArgumentNullException(nameof(postCode));
    return customers.Where(c => c.PostCode == postCode);
}
C#
IEnumerable<Customer> SearchCustomers(string postCode)
{
    if (postCode == null)
        throw new ArgumentNullException("postCode");
    return customers.Where(c => c.PostCode == postCode);
}

Notes

  • CallerArgumentExpression C# 10.0 allows the name to be captured automatically
  • The .NET CLR takes advantage of this to provide static helpers like ArgumentNullException.ThrowIfNull(postcode)

More information