Thanks to everyone who came along to my DEV311 at TechEd New Zealand yesterday. Here’s the low down on the snippets demo that didn’t work the way it should on the day …

Notifying Properties

Creating a property that triggers the PropertyChanged event isn’t difficult, but it is mindless boilerplate. The propn snippet makes it really easy to write with just a few keystrokes.

Here’s the output of using the snippet to declare a FullName property:

public string FullName
{
    get { return mFullName; }
    set
    {
        if (!Object.Equals(mFullName, value))
        {
            mFullName = value;
            OnPropertyChanged();
        }
    }
}

private string mFullName;

Note that this is triggering the OnPropertyChanged() method with no parameters, expecting it to use the new [CallerMemberName] attribute introduced in .NET 4.5.

INotifyPropertyChanged Implementation

The supporting infrastructure for the INotifyPropertyChanged event is also boilerplate - hence the notify snippet that produces this code:

public event PropertyChangedEventHandler PropertyChanged
{
    add { mPropertyChanged += value; }
    remove { mPropertyChanged -= value; }
}

private void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
    var handlers = mPropertyChanged;
    if (handlers != null)
    {
        handlers(this, new PropertyChangedEventArgs(propertyName));
    }
}

private PropertyChangedEventHandler mPropertyChanged;

Between notify and propn, writing the infrastructure to support databinding is a whole lot easier.

Next Post
Everything's broken but we can fix it  21 Sep 2012
Prior Post
The best ORM that you've never used  18 Aug 2012
Related Posts
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
Archives
September 2012
2012