Using nameof Operator  in C# 6.0

Using nameof Operator in C# 6.0

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));
}
}
Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

6 Comments to “Using nameof Operator in C# 6.0”

Comments are closed.