Archive for January, 2016

C# 6.0 – nameof Operator

Posted: January 1, 2016 in .NET, C#
Tags: ,

In this post, we will discuss about the C# 6.0 nameof operator.

In the code snippet below we are trying to the details i.e Class & method names whenever a method is invoked. In real life applications we do similar kind of logging using any logging library.

image

The issue here is we have used string literals to refer to the class and method names. As the number of methods and corresponding log entries increases it becomes difficult to track these and also typos etc. may creep in creating more clutter.

In C# 6.0 the nameof operator gives us a provision to get the names of classes, methods,properties, variables etc. in the form of unqualified strings. The changed version of the code using nameof operator is shown below:

image

This gives as better manageability as the tools and IDE can have better track of these names now. Suppose I am renaming the class in that case Visual Studio track this down very easily as shown in the figure below

image

As obvious this is nothing but a very handy syntactic sugar coat. If we take a look into the IL code, we can easily see nothing heavy duty is going on inside. The compiler is simply replacing the nameof calls by the unqualified string literal name of the class and the method.

 

image