ReSharper live template for an INPC property

I’ve considered ReSharper a must-have for Visual Studio for many years, and their live templates are code snippets on steroids. Here I share with you my simple but effective template for generating properties. What it does is add the backing field in camelCase (with an underscore) matching your public name written in PascalCase. All you have to do is input the type name and the public name.

INPC (INotifyPropertyChanged) is the standard way for a ViewModel to communicate with a data bound UI, and the notifications can be quite tedious to write.

/* UPDATE 2013-02-06

Here is the body of the template using the Windows 8 template pattern with SetProperty(ref field, value):

public $RETURN_TYPE$ $NAME$
{
    get { return _$BACKING_FIELD$; }
    set { SetProperty(ref _$BACKING_FIELD$, value); }   
}
private $RETURN_TYPE$ _$BACKING_FIELD$;
$END$

       

END UPDATE */

How to use

Firstly import the template, then you can use the snippet by:

  • type propn
  • hit tab
  • type the property type, e.g. string
  • hit tab
  • type the property public name, e.g. Amount
  • hit tab,tab

You now have a full property with INPC notification. The actual notification uses the method NotifyOfPropertyChange from helper classes in Caliburn Micro. They have a really sweet sub-package with just a few helper classes in a code drop-in available via nuget.

Usage 1/3

Usage 2/3

Usage 3/3

The template in the ReSharper editor

This Post Has 6 Comments

  1. So how exactly does it improve on the basic code snippets? Does it automatically camel-case the backing field name when you type in a Pascal-cased property name?

  2. Yes it does, thanks for pointing it out. I’ll clarify that in the post.

  3. Bra template, men kan inte ta hem.

  4. Awesome! Thank you Andreas!

Leave a Reply

Close Menu