Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of nameof?

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?

like image 382
atikot Avatar asked Jul 29 '15 09:07

atikot


1 Answers

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)

like image 71
Patrick Hofman Avatar answered Sep 18 '22 20:09

Patrick Hofman