Visual Studio 2015, .NET 4.6 and C# 6.0 came up with lot many features. If you didn’t try the new IDE, download the preview version in a non-production environment to get your hands dirty with it. You will definitely love the new features.
Today in this post, we will learn about another new feature called “
nameof” expression which will surely solve most of the problems a developer faces when playing with properties and notifications.
Don’t forget to read my previous posts on this series:
Most of the time, developer faces issues with hard coded
string literals when passing them as parameter to exception object or to property change event handler. If you are a developer working in any of the XAML technologies, you might already know the pain. If becomes harder when in different file different names were used or sometimes, a misspelled word used while passing the property name to the
PropertyChanged event handler for sending the notification to the UI.
Earlier to C# 6.0, just have a flash back to see how we implemented this. We pass the
string name literal to the event handler method as shown below and most of the time, there’s a possibility of a misspelled word:
But now, things got changed. You don’t have to specify any
string literals here. Wondering how this can be achievable then? Now in C# 6.0, we have a new keyword named “
nameof” which you can use to create the expression to specify the name. You just have to set the property to the
nameof expression and it will do the magic and return a
nameof(Person) will return you
string literal “
nameof(person.Address.City) will return you
string literal “
City”. Here’s a code snippet to show you the implementation steps in your code and I am sure that this will reduce your burden over time. Isn’t it?
Hope you liked the feature introduced by Microsoft in C# 6.0. Don’t forget to read my other posts on the same topic “What’s new in C# 6.0?” to find out all the new features introduced in C# 6.0 with Visual Studio 2015 and .NET 4.6. This post was created demonstrating the same in Visual Studio 2015 Preview build, which might change in the final build.
Connect with me over Facebook, Twitter, Google+ and/or LinkedIn to get the updates that I share regularly. Subscribe to my blog’s RSS feed and Email Newsletter to get the immediate update about new article submission. Happy coding!