atikot atikot - 1 year ago 68
C# Question

What is the purpose of nameof?

Version 6.0 got a new feature of

, 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
but when I try to
it just prints me a
instead of the used type.

Any idea on the purpose?

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download