Skip to content

Instantly share code, notes, and snippets.

@mwinckler
Created August 21, 2012 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwinckler/3417914 to your computer and use it in GitHub Desktop.
Save mwinckler/3417914 to your computer and use it in GitHub Desktop.
Regex to generate C# INotifyPropertyChanged-compliant properties

Start with a list that looks like this:

public string MyProperty
public int MySecondProperty
public bool HoweverManyPropertiesYouWant

...then run a Find/Replace using regular expressions as follows:

Find:

^\s+public ([^ ]+) ([^ ]+).*$

Replace with:

\1protected \2 _\l\3;\n\1public \2 \3 \{\n\1\tget \{ return _\l\3; \}\n\1\tset \{\n\1\t\tif \(value != _\l\3) \{\n\1\t\t\t_\l\3 = value;\n\1\t\t\tthis.OnPropertyChanged("\3");\n\1\t\t\}\n\1\t\}\n\1\}\n

Note that this will not work with Visual Studio's search-and-replace because Microsoft is too clever to simply accept a good thing like PCRE-compatible syntax and has to come up with its own bastardized version (and I'm too lazy to translate working regexes into broken MS syntax). Use the above regexes in a sensible editor such as Sublime Text 2.

Also, this assumes the class has a function called OnPropertyChanged which will do the actual notifications. Mine usually looks something like this:

protected void OnPropertyChanged(string propName) {
	var x = this.PropertyChanged;
	if (x != null) {
		x(this, new PropertyChangedEventArgs(propName));
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment