Skip to content

nameof operator C# 6.0correctness

Capture the name of a variable, type or member 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 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 ​

More information ​

Powered by Intracia