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 nameofoperator 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.

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

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.

Share this:

About 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.