C# – the purpose of nameof

cc#-6.0nameofnet

Version 6.0 got a new feature of nameof, but I can't understand the purpose of it, as it just takes the variable name and changes it to a string on compilation.

I thought it might have some purpose when using <T> but when I try to nameof(T) it just prints me a T instead of the used type.

Any idea on the purpose?

Best Answer

What about cases where you want to reuse the name of a property, for example when throwing exception based on a property name, or handling a PropertyChanged event. There are numerous cases where you would want to have the name of the property.

Take this example:

switch (e.PropertyName)
{
    case nameof(SomeProperty):
    { break; }

    // opposed to
    case "SomeOtherProperty":
    { break; }
}

In the first case, renaming SomeProperty will cause a compilation error if you don't change both the property definition and the nameof(SomeProperty) expression. In the second case, renaming SomeOtherProperty or altering the "SomeOtherProperty" string will result in silently broken runtime behavior, with no error or warning at build time.

This is a very useful way to keep your code compiling and bug free (sort-of).

(A very nice article from Eric Lippert why infoof didn't make it, while nameof did)