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.


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:


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


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.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s