What is the purpose of nameof?

atikot picture atikot · Jul 29, 2015 · Viewed 155.3k times · Source

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?

Answer

Patrick Hofman picture Patrick Hofman · Jul 29, 2015

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 change the name of the property too, or it will break compilation. The last case doesn't.

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)