Today I am going to show you how to use a regular expression with back reference matching to quickly replace all occurrences of magic strings to strong type names.
In my WPF project I had a method which was connected to the INotifyPropertyChanged interface and notified the WPF binder whenever a property on my model was changed. This method took as a parameter the name of the property to refresh.
So calling this method in a simplest way looked like this
Thanksfully there came an improvements. With C# 6.0 they introduced a nameof function which takes the member of a class and returns a string representing that name. So all has to be done is to change above call to this
Great. Now we don’t need to worry anymore about the refactoring of a property name.
The problem is when this is a huge project and there are many places where the nameof method has to be introduced. Fortunatelly there is a search and replace and the regular expressions.
In Visual Studio hit Ctrl + H to invoke a search and replace window.
As a pattern to search type in this
and as a replacement type in this
Notice that the search pattern matches only valid C# members identifiers.