INotifyPropertyChanged with less code using Expressions

Technorati Tags:,,

Parts 1 & 2 of this unintended trilogy:

My previous post elicited a couple of good comments.

Matt noted that my use of reflection to get the property name could be a problem in due to inlining in Release  mode:

Jérôme and Mark suggested that an Expression might be a better solution than reflection. Here's what that could look like:

My shared method to update property backing variables and raise the INotifyPropertyChanged.PropertyChanged event:

protected bool CheckForPropertyChange(T value, ref T currentValue, Expression<Func> expr)

{

if (value.Equals(currentValue)) return false;

currentValue = value;

if (PropertyChanged!= null)

{

var body = expr.Body as MemberExpression;

if (body!= null)

{

PropertyChanged(this, new PropertyChangedEventArgs(body.Member.Name));

}

}

return true;

}

...and properties using it:

private string _CustomerName;

public string CustomerName

{

get { return _CustomerName; }

set { CheckForPropertyChange(value, ref _CustomerName, => CustomerName); }

}

private string _PhoneNumber;

public string PhoneNumber

{

get { return _PhoneNumber; }

set { CheckForPropertyChange(value, ref _PhoneNumber, => PhoneNumber); }

}

Using the lambda (e.g. " => CustomerName") to specify the property name is an improvement over a hardcoded string because the compiler validates it and it's "refactorable". As Jérôme pointed out on his blog, the lambda is not actually called, just used by the CheckForPropertyChange method to determine the property name.

This article is part of the GWB Archives. Original Author: Brian Schroer

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.