One of the Visual Studios functionalities 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 especially useful when working with MVVM or/and WPF, most likely because there is more than one way to implement such a property.

That doesn’t mean I cannot write my own:

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

And the class implementing 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:

propo.snippet

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Observable property</Title>
      <Description>Adds a new observable property to the current class.</Description>
      <Shortcut>propo</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>Type</ID>
          <ToolTip>Replace with the type you want your property to have.</ToolTip>
          <Default>PropertyType</Default>
        </Literal>
        <Literal>
          <ID>Name</ID>
          <ToolTip>Replace with the name you want to give to the property.</ToolTip>
          <Default>PropertyName</Default>
        </Literal>
      </Declarations>
      <Code Language="CSharp">
        <![CDATA[private $Type$ _$Name$;
        public $Type$ $Name$
        {
            get { return _$Name$; }
            set
            {
                if (_$Name$ != value)
                {
                    _$Name$ = value;
                    RaisePropertyChanged("$Name$");
                }
            }
        }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

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.