Notifying Property Code Snippet

Having worked in Silverlight for a little over a year now, I find that INotifyPropertyChanged and the corresponding PropertyChanged event are something I use pretty often. To manage that I created a base view model class that exposes the following wrapper method:

/// <summary>
/// Raised when a property changed notification is sent.
/// </summary>
/// <param name="propertyName" />
/// A <see cref="System.String" /> identifying the property that 
/// changed.
/// </param>
protected void OnPropertyChanged(string propertyName)
    if (PropertyChanged != null)
            new PropertyChangedEventArgs(propertyName));

This allows me to create properties that look like:

/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>
/// A string that contains the Name.
/// </value>
public string Name
    get { return _name; }
        if (_name == value) return;
        _name = value;

That’s still a lot of typing! More typing is less doing. To add these properties more efficiently I developed the following code snippet:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="">
    <CodeSnippet Format="1.0.0">
                Notifying Property
                    <ToolTip>The property type.</ToolTip>
                    <ToolTip>The property name.</ToolTip>
                    <ToolTip>The variable name.</ToolTip>
            <Code Language="CSharp">
        <![CDATA[/// <summary>
        /// Gets or sets the $propname$.
        /// </summary>
        /// <value>
        /// A $type$ that contains the $propname$.
        /// </value>
        public $type$ $propname$
            get { return $varname$; }
                if ($varname$ == value) return;
                $varname$ = value;

Now I can just type propnotify and press Tab to get a template property snippet in my code. This saves a bunch of time when declaring the notifying bound properties within a view model.

propnotify  propnotify2

What interesting code snippets have you developed? Do you rely upon a third-party tool such as Resharper or CodeRush, or does the snippet system in Visual Studio 2010 meet your needs?

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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