Kathleen Dollard put together a post on INotifyPropertyChanged. It uses the CallerMemberName feature on .NET 4.5, something I previously wrote about.
Kathleen’s version is nice, and it does remove the “magic string” of naming the changed member. Still I think I’ll go with my version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| public abstract class ViewModelBase
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(Expression<Func<object>> path)
{
string propertyName = ReflectionUtil.GetPropertyName(path);
OnPropertyChanged(propertyName);
}
protected void OnPropertyChanged(string propertyName)
{
Debug.WriteLine("Property Changed: " + propertyName);
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
|
Hmmmm… Now what do you think ReflectionUtil.GetPropertyName does exactly? I wonder…
1
2
3
4
5
6
7
8
9
10
11
12
13
| public static string GetPropertyName(Expression<Func<object>> expression)
{
if (expression == null)
throw new ArgumentNullException("expression");
Expression body = expression.Body;
MemberExpression memberExpression = body as MemberExpression;
if (memberExpression == null)
{
memberExpression = (MemberExpression)((UnaryExpression)body).Operand;
}
return memberExpression.Member.Name;
}
|
This makes for a really simple usage. Here’s an example property from a view model class.
1
2
3
4
5
6
7
8
9
10
11
12
| public string FirstName
{
get { return firsName; }
set
{
if (firstName != value)
{
firstName = value;
OnPropertyChanged(() => FirstName);
}
}
}
|
So there’s my version. No magic strings. No .NET 4.5 compiler magic. Just plain old .NET 3 expression tree magic.