C# 6.0 Language Features – nameof Operator

Welcome to C# 6.0 language features article series. As you might have heard about Visual Studio 2015 and .Net framework 4.6 announcements in various Microsoft events earlier, one of the most exciting news was the next version of C# language, which is 6.0 and new features added to it. C# has come a long way since 2002 when C# 1.0 was released along with Visual Studio. Since then with every major release of .Net framework, C# became better and better language, which has tremendously helped application developers to minimize the code complexity and focus on business functionality. With the new version of .Net framework and Visual Studio around the corner, you can start learning new language features today using Visual Studio 2015 preview release. There are many useful features added to the language and I don’t know at the moment, how many articles I will write in this series, but it will probably something like this.

  1. Static using statements
  2. Auto property initializer
  3. Null conditional operator
  4. String interpolation
  5. nameof operator – This article
  6. Declaration expressions

nameof Operator

One of the common [bad] practices in any programming language is to use magic string within application program; however there are certain scenarios in which you cannot avoid using it. In some cases, such magic string refers to a specific element within the program. For e.g. while raising ArgumentNullException exception, we need to pass which argument cannot be null using a magic string.

static void DisplayName (string username)   
{   
    if (username== null)   
    throw new ArgumentNullException("Username value cannot be null");   
}

Similarly if you have done any XAML programming using MVVM pattern, you should be familiar with INotifyPropertyChanged interface and you must have passed property name as a magic string to OnPropertyChanged event handler as shown in below code snippet.

public class CustomerViewModel : INotifyPropertyChanged
    {
        private int firstName;
        public int FirstName
        {
            get { return firstName; }
            set 
            { 
                firstName = value;
                OnPropertyChanged("FirstName");
            }
        }

        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
}

Although there is nothing wrong in doing so, C# compiler cannot validate if these magic strings refers to appropriate program element. For e.g. if you rename the FirstName property in above code snippet, there is no way C# compiler can update the magic string in property setter based on the changes made…until C# 6.0.

The nameof operator allows developers to use a program element as text. You cannot specify a string literal / magic string directly with the nameof operator. It can be used to create the nameof expression to specify the name where expression may be a property-group or a method-group.

If you rename username parameter in the DisplayName function below,

static void DisplayName (string username)   
{   
    if (name== null)   
    throw new ArgumentNullException(nameof(username));   
}

If you rename the username parameter, you will also need to update the nameof expression otherwise program will not compile.

Similarly, we can also update the INotifyPropertyChanged property setter code to ensure that we can use nameof operator to refer to exact program element instead of a magic string.

public string FirstName
{
    get { return firstName; }
    set
        {
            if (firstName != value)
            {
                firstName = value;
                OnPropertyChanged(nameof(FirstName));
            };
        }
}

I believe this feature will help developers to write cleaner and readable code. Let me know what you think about it in the comments section below.

Leave a Reply