Replace all magic string with just one regex

By Mirek on (tags: INotifyPropertyChanged, nameof, regex, visual studio, categories: tools)

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.

public void NotifyPropertyChanged(string propertyName);

So calling this method in a simplest way looked like this

NotifyPropertyChanged("MyProperty");

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

NotifyPropertyChanged(nameof(MyProperty));

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.

image

As a pattern to search type in this

NotifyPropertyChanged\("([A-Za-z_][A-Za-z_0-9]*)\b"\);

and as a replacement type in this

NotifyPropertyChanged(nameof($1));

Notice that the search pattern matches only valid C# members identifiers.