Click here to Skip to main content
15,120,078 members
Articles / Programming Languages / C#
Tip/Trick
Posted 5 May 2015

Tagged as

Stats

39.5K views
16 bookmarked

Nameof Operator: A New Feature of C# 6.0

Rate me:
Please Sign up or sign in to vote.
4.80/5 (17 votes)
5 May 2015CPOL2 min read
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

arora.abhishek
Tester / Quality Assurance
India India
Hello this is Abhishek working as a Software Test Engineer

Comments and Discussions

 
Generalomg Pin
Octanic10-May-15 9:38
MemberOctanic10-May-15 9:38 
QuestionDemo Application 2 Pin
Alex (RSA)6-May-15 19:32
professionalAlex (RSA)6-May-15 19:32 
QuestionOn use of the operator with reference types vs value types Pin
jfriedman6-May-15 3:34
Memberjfriedman6-May-15 3:34 
Cool article, just wanted to add my opinion / comment.

Take for example the following:

var x = "Anything";

System.Console.WriteLine(nameof(x)); // "x"

var y = x;

System.Console.WriteLine(nameof(y)); // "y"

With ValueTypes the result is copied, this is easy to understand.

Object o = new object();

System.Console.WriteLine(nameof(o)); // "o"

Object b = o;

System.Console.WriteLine(nameof(b)); // "b"

With a reference type the result is not copied and the variable simply only refers to the object, however the variable has it's own name.

I would have imagined that another useful operator would be IsReferenceOf however we already have Object.ReferenceEquals.

In short, this 'nameof' operator only is only providing you a syntactic sugar to something you could have already accomplished (albeit probably with slightly less overhead).

Also, depending on how code obfuscation is used that operator may also cause you some trouble down the line, but then again maybe not.

Poke tongue | ;-P
GeneralHelpful article Pin
MayurDighe6-May-15 1:13
professionalMayurDighe6-May-15 1:13 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun5-May-15 18:57
MemberHumayun Kabir Mamun5-May-15 18:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.