Observable Property C# code snippet

One of the VS functionality I abuse every day is writing code via the code snippets, those little fill-in code pieces that appear when you press tab twice after writing their mnemonic like propdp[Tab][Tab] for defining a DependencyProperty.

Unfortunately, VS doesn’t come with such a snippet for defining an observable property, which might be particular useful when working with MVVM or/and WPF, most likely because there is more than one way to implement such a property. However, I usually implement them in the same way, something like this:

private string _Name;
public string Name
    get { return _Name; }
        if (_Name != value)
            _Name = value;

And the class implements INotifyPropertyChanged and RaisePropertyChanged looks like this:

public void RaisePropertyChanged(params string properties)
    var handler = PropertyChanged;
    if (handler != null)
        handler(this, new PropertyChangedEventArgs(prop));

In this conditions, when I have to write a lot of observable properties (actually I am using it even if I have to write only one such property), it comes very handy to have a code snippet that generates the property:


<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
      <Title>Observable property</Title>
      <Description>Adds a new observable property to the current class.</Description>
          <ToolTip>Replace with the type you want your property to have.</ToolTip>
          <ToolTip>Replace with the name you want to give to the property.</ToolTip>
      <Code Language="CSharp">
        <![CDATA[private $Type$ _$Name$;
        public $Type$ $Name$
            get { return _$Name$; }
                if (_$Name$ != value)
                    _$Name$ = value;
To install this snippet, save the above xml in a file called propo.snippet and use the Import button in the Visual Studio’s Code Snippets Manager (Tools / Code Snippets Manager).
To use this snippet write propo in a cs file and hit Tab key twice.

Leave a Reply

Your email address will not be published. Required fields are marked *