Bhavya

Code -> Break -> Fix -> Blog

C# 6.0 : nameof Operator

1 Comment

With the introduction of nameof operator, a developer can reduce the use of string literals for program elements like class, field, property etc.

Say we have a method which checks the Name property and if Name property has any numeric character then the method throws an ArgumentException stating “Name property is invalid.”

 // Code which checks if name holds only alphabets
 // and no numberic characters.
 // If name parameter has numeric characters then
 // throw Argument exception.
 ...
 ...
 catch(ArgumentException)
 {
 WriteLine("Name property is invalid.");
 }

If the developer modifies the Name property to FullName. The compiler will not warn the developer to update the string literal which will end up confusing the end-user or we will have an invalid entry in the log (if the string is used for logging).

With C# 6.0 and nameof operator, this can be avoided.

Console.WriteLine(nameof(FullName) + " property is invalid.");

nameof operator can be really useful when calling the OnPropertyChanged().

Instead of :

 public string FullName
 {
 get
 {
 return fullName;
 }
 set
 {
 fullName = value;
 // Call OnPropertyChanged whenever the property is updated
 OnPropertyChanged("FullName");
 }
 }

the developer can now use the nameof operator

  public string FullName
 {
 get
 {
 return fullName;
 }
 set
 {
 fullName = value;
 // Call OnPropertyChanged whenever the property is updated
 OnPropertyChanged(nameof(FullName));
 }
 }

The nameof operator takes a class, method, field, property or variable and returns a string literal.

Let me know your thoughts.

~BS

Twitter Logo

Advertisements

One thought on “C# 6.0 : nameof Operator

  1. Pingback: New Features of C# 6.0 | Bhavya

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s