C# 6 features – nameof


Recent release of C# 6 and Visual Studio 2015 introduced many useful features. I’ll try do describe all of them. The first for today is support for nameof expressions.

There are several occasions when you’ll need to use ‘special strings’ in code. Such ‘special strings’ are regular C# strings that map to program elements in code.

For example, when throwing an ArgumentNullException, you’d use a string for the name of the corresponding parameter that was invalid. Unfortunately, these special strings had no compile time validation. If a program element changes (rename the parameter) it wouldn’t automatically update the special string, resulting in inconsistency.

C# 6.0 provides access to a ‘program element’ name to address the issue. A class name, method name, parameter name or particular attribute name can be used with nameof expression to extract it’s name.

void MethodWithParameter(string param1)
    if (param1 == null)
        throw new ArgumentNullException(nameof(param1)); // Name of variable

    // More code

Value returned by nameof(param1) is “param1” string. The nameof expression isn’t limited to parameters. Here are other examples.

using System;

namespace NameOfExampleApp
    class Program
        static void Main(string[] args)
            Console.WriteLine(nameof(Main));                   // Name of method
            Console.WriteLine(nameof(Program));                // Name of class
            Console.WriteLine(nameof(NameOfExampleApp));       // Name of namespace
            Console.WriteLine(nameof(System.Threading.Tasks)); // Name of namespace

The output:


Last example shows that nameof is not created as a fully qualified name (System.Threading.Tasks), but picks only the last identifier (Tasks) even if more explicit name was used.



Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One thought on “C# 6 features – nameof