Strongly-typed Names for INotifyPropertyChanged

A number of people have asked whether it is possible to implement INotifyPropertyChanged without hard-coding property names as strings inside code.

For example, you would normally write:

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
    }
}

Unfortunately the default refactoring tools won't search in string literals, so if LastName was renamed to Surname, you'd need to change the string manually.

One option to enforce compile-time detection would be the following:

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(Property.GetFor( () => this.Name ));
    }
}

It could be implemented quite simply with the following static method:

public class Property
{
    public static PropertyChangedEventArgs GetFor(Expression<Func<object>> propertyNameLambda)
    {
        MemberExpression member = propertyNameLambda.Body as MemberExpression;
        if (member != null)
        {
            return new PropertyChangedEventArgs(member.Member.Name);
        }
        return new PropertyChangedEventArgs("");
    }
}

Personally, I don't mind hard-coding property names too much, but it's hardly a best practices, so you may find the above useful. Just beware that it does come with some overhead at runtime.

A picture of me

Welcome, my name is Paul Stovell. I live in Brisbane and work on Octopus Deploy, an automated deployment tool for .NET applications.

Prior to founding Octopus Deploy, I worked for an investment bank in London building WPF applications, and before that I worked for Readify, an Australian .NET consulting firm. I also worked on a number of open source projects and was an active user group presenter. I was a Microsoft MVP for WPF from 2006 to 2013.