Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Nameof Operator: A New Feature of C# 6.0

0.00/5 (No votes)
5 May 2015 1  
In this tip, we will learn about the new features of the C# 6.0 nameof operator

Introduction

On November 12, 2014, the day of Visual Studio Connect() event, Microsoft announced Visual Studio 2015 preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0 that came with many improvements and new features. One of the newly introduced features of C# 6.0 is the nameof Operator.

What is nameof Operator

With the introduction of the nameof operator, the hard-coded string to be specified in our code can be avoided. The nameof operator accepts the name of code elements and returns a string literal of the same element. The parameters that the nameof operator can take can be a class name and all its members like methods, variables and constants and returns the string literal.

Using string literals for the purpose of throwing an ArgumentNullException (to name the guilty argument) and raising a PropertyChanged event (to name the property that changed) is simple, but error prone because we may spell it wrong, or a refactoring may leave it stale. The nameof operator expressions are a special kind of string literal where the compiler checks that you have something of the given name and Visual Studio knows where it refers to, so navigation and refactoring will work easily.

The nameof Operator can be useful with multiple scenarios, such as INotifyPropertyChanged, ArgumentNullException and reflection.

Example 1

C#
string person;
Console.WriteLine(nameof(person)); // prints person
int x = 2;
Console.WriteLine(nameof(x));     //prints x

Example 2

C#
public operatornameof(string name) //constructor
{
   if (name == null)
      throw new ArgumentNullException(nameof(name)); // use of nameof Operator
   else
      Console.WriteLine("Name: " + name);
}

Example 3

C#
private int _price;
public int price
{
   get
   {
      return this._price;
   }
   set
   {
      this._price = value;
      PropertyChanged(this,
                   new PropertyChangedEventArgs(nameof(this.price)));   //// INotifyPropertyChanged
   }
}

Demo Application 1 using Visual Studio 2013

C#
using System;
using System.Text;

namespace CSharpFeatures
{
    public class operatornameof
    {
        public operatornameof(string name, string location, string age)
        {
            if (name == null)
                throw new ArgumentNullException("name");
            else
                Console.WriteLine("\n Name: " + name);
            if (location == null)
                throw new ArgumentNullException("location");
            else
                Console.WriteLine(" Location: " + location);
            if (age == null)
                throw new ArgumentNullException("age");
            else
                Console.WriteLine(" Age: " + age);
        }
        static void Main(String[] args)
        {
            operatornameof p = new operatornameof("Abhishek", "Ghaziabad", "23");
            Console.ReadKey();
        }
    }
}

Demo Application 1 using Visual Studio 2015 Preview

C#
using System;
using System.Text;

namespace CSharpFeatures
{
    public class operatornameof
    {
        public operatornameof(string name, string location, string age)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            else
                Console.WriteLine("Name: " + name);
            if (location == null)
                throw new ArgumentNullException(nameof(location));
            else
                Console.WriteLine("Location: " + location);
            if (age == null)
                throw new ArgumentNullException(nameof(age));
            else
                Console.WriteLine("Age: " + age);
        }
        static void Main(String[] args)
        {
            operatornameof p = new operatornameof("Abhishek", "Ghaziabad", "23");
            Console.Read();
        }
    }
}

Demo Application 2 using Visual Studio 2013

C#
using System;

namespace CSharpFeatures
{
    class Operatornameof1
    {
        static void Main(string[] args)
        {
            details d = new details();
            d.Age = 23;
            d.Name = "Abhishek";
            Console.WriteLine("\n Name: {0} ", d.Name);
            Console.WriteLine(" Age: {0} ", d.Age);
            Console.ReadKey();
        }
    }
    class details
    {
        private string _Name;
        public int _Age;
        public string Name
        {
            get { return this._Name; }
            set { this._Name = value; }
        }
        public int Age
        {
            get { return this._Age; }
            set { this._Age = value; }
        }
    }
}

Demo Application 2 using Visual Studio 2015 Preview

C#
using System;

namespace CSharpFeatures
{
    class Operatornameof2
    {
        static void Main(string[] args)
        {
            details d = new details();
            Console.WriteLine("{0} : {1}", nameof(details.Name), d.Name);
            Console.WriteLine("{0} : {1}", nameof(details.Age), d.Age);
            Console.ReadKey();
        }
    }
    class details
    {
        public string Name { get; set; } = "Abhishek";
        public int Age { get; set; } = 23;
    }
}

Summary

In this tip, we learned how to use the nameof operator to avoid the use of hard-coded strings in our code. I hope you liked this new feature of C# 6.0 introduced by Microsoft. Don't forget to read my other articles on the series "A new feature of C# 6.0" . Share your opinion about this feature and how you will use it in your project? Your comments are most welcome.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here