nameof Expression in C# 6.0

This function is one of the useful addtion to the language in C# 6.0 and will see a widespread adoption. We as developers have written many times the below code numerous times in our life.

In this basically we are checking whether the parameters are properly set according the business rules and if it's not then throws the ArgumentNull exception with the message saying that this particular property is not set.

Suppose after some time we decided to change the name of the properties, went ahead with using the refactoring options available in Visual Studio. In the example I removed the term Product from all the properties using the refactoring option, but the messages for the ArgumentNull exception won't change since it's inside string literals.

Now when the exception occurs there is a mismatch between the actual property name and the name in the message. Imagine if this occurs in a class containing a lot of properties then it take some time to make the corrections and also there's a possiblity of missing out on some.

That's when the nameof expression in C# 6.0 comes handy. Let's see how can we refactor the above code using nameof

Here in this example instead of hard coding the name of the properties in the string, I used the nameof expression which will actually return the name of the underlying property to show the correct message. Many of you may be wondering why I am using a $ symbol in front of the string and how can I use the C# syntax inside the string which is later transformed into the correct message during execution of the code. It's the new String interpolation feature in C# 6.0 and you read more about it here.

No Comments

Add a Comment