How to use strongly-typed name with INotifyPropertyChanged

You may already have read my posts about how to use INotifyPropertyChanged in a type-safe way (here and here), but sometime you don’t want to modify all your classes to use this method. All you want is avoid the use of a magic string to define the property. Your code will be refactoring proof.

For example let say you have this property:

Some refactoring tool, like Resharper, will be able to change the “FirstName” string but not Visual Studio itself. The solution? Replace this string with a strong type value. How? Let’s assume we can do this:

Notice that you must specify the “this” keyword to make it work. That is exactly What this extension method let you do:

You can even use it in your property changed handler:

Enjoy!


2 thoughts on “How to use strongly-typed name with INotifyPropertyChanged

  1. protected void Notify(T obj, Expression> selector)
    {
    if (propertyChangedEvent != null)
    {
    MemberExpression memberExpression = selector.Body as MemberExpression;
    if (memberExpression == null)
    {
    UnaryExpression unary = selector.Body as UnaryExpression;
    if (unary != null)
    {
    memberExpression = unary.Operand as MemberExpression;
    }
    }

    if (memberExpression == null)
    throw new ArgumentException(“member should be of MemberExpression type”, “selector”);

    propertyChangedEvent(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
    }
    }
    Then use

    Notify(this, o=> o.PropertyName);

Leave a Reply