Using nameof Operator in C# 6.0

By | December 9, 2014

C# 6.0 introduced a new operator named, nameof  that accepts the name of code element and returns a string literal of the same element.  The nameof operator can take as a parameter like class name and its all members like method, variables, properties and return the string literal.  This avoids having hardcoded strings to be specified in our code as well as avoid explicitly use of reflection to get the names.

image

Below is the simple code snippets that show the uses of nameof operator.

class Program
{
static void Main(string[] args)
{
WriteLine(nameof(Student));
WriteLine(nameof(Student.Roll));
WriteLine(nameof(Student.Name));
WriteLine(nameof(Student.Address));
}
}

class Student
{
public int Roll { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}

If you are wondering, How I am calling the static method WriteLine() directly instead of ussing Console.WriteLine(), you must check Simplify Static Member Access – Using Statement With Static Classes in C# 6.0

The output would be like below :

One of the common uses of this operator could in NotifyPropertyChanged Event Handler or calling PropertyChanged() event. We generally pass the hardcoded Property name for the event handler that notify the UI on property changes. Now using C# 6.0, you can easily get the string literal using the nameof Operator.

 

Earlier :


public string UserName
{
get
{
return _userName;
}
set
{
this.OnPropertyChanged("UserName");
}
}

Now : With C# 6.0 nameof Operator

public string UserName
{
get
{
return _userName;
}
set
{
this.OnPropertyChanged(nameof(UserName));
}
}

6 thoughts on “Using nameof Operator in C# 6.0

  1. Pingback: Null – Conditional Operators in C# 6.0

  2. Pingback: Download PPT – “A lap around C# 6.0 and Visual Studio 2015 Preview” – MUGH Dev Day– 29th Nov 2014 | Abhijit's World of .NET

  3. Pingback: 10 New features of C# 6.0 that you should know | Abhijit's World of .NET

Comments are closed.