C# 6 and the nameof(x) operator

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.
image

With the new nameof operator you can use this:
image

The nameof operator will be executed at compile time. This is how the above code looks in IL Spy:
image
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.
image

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:
image

The result of nameof(MyEnum.Value0) gets directly written to the IL code.


Posted Dec 01 2015, 03:49 PM by Holger Vetter
Filed under: ,
developers.de is a .Net Community Blog powered by daenet GmbH.