In C# 6 the new operator nameof was introduced. It helps the developer to use any property/classname/namespace and so on as a string. The string will be set at compile time.
Lets start with some examples.:
When checking arguments before C# 6 you had to use the following to output the argument name which was not set or had an invalid value.
With the new nameof operator you can use this:
The nameof operator will be executed at compile time. This is how the above code looks in IL Spy:
As we can see, the compiler inserted for nameof(args) “args”.
It doesn’t look like a revolution, but for me it is a very handy feature.
Everytime you need the name of a property/class or a namespace you can use nameof().
This also allows you to use this for enums.
Before nameof() you had to use the .ToString() method with costs processing time. Now you can just use the new C# feature and the value gets evaluated at compile time. Here is the difference in IL Spy:
The result of nameof(MyEnum.Value0) gets directly written to the IL code.
Posted
Dec 01 2015, 03:49 PM
by
Holger Vetter