NameOf Keyword and it’s internals

NameOf keyword has been introduced in c# 6.0. NameOf keyword will take the variable name and changes into string while compilation.

You might be wondering, what’s the use of this keyword. It comes handy, when you are using WPF(propertyChange handler), switch statement, events etc.

Let’s go through the code snippets

public class Employee : INotifyPropertyChanged
{
private int _id;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged(“Id”);
}
}

public event PropertyChangedEventHandler PropertyChanged;

public Employee()
{
PropertyChanged += (o, e) => { };
}

public void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

As a WPF developer, i know the pain of hard coded strings in OnPropertyChanged method. In the future, if you decide to change the name of property and if in case you forget to update the OnPropertyChanged(“Id”) then you will get binding error.

In previous version of .net framework, we used expression tree in order to avoid binding error as mentioned above. But today, we can happily say that we have nameOf keyword.

Now the above code snippet looks like this

public class Employee : INotifyPropertyChanged
{
private int _id;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged(nameof(Id));
}
}

Rest of the other code remains the same.

Now, if you check the above snippet in decompiler(dotPeek)

public class Employee : INotifyPropertyChanged
{
private int _id;
public int Id
{
get
{
return this._id;
}
set
{
this._id = value;
this.OnPropertyChanged(“Id”);
}
}

public event PropertyChangedEventHandler PropertyChanged;

public Employee()
{
this.PropertyChanged += (PropertyChangedEventHandler) ((o, e) => {});
}

public void OnPropertyChanged(string propertyName)
{
// ISSUE: reference to a compiler-generated field
this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName));
}

By looking at the decompiled code, you can verify the above definition is correct i.e at the compile time, it will replace the variable name with string.

Hope you enjoyed the article. Cheers!

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s