RSS
 

Archive for September, 2011

Raising the right PropertyChanged with C# 5’s Caller Info Attributes

21 Sep
Implementing INotifyPropertyChanged typically requires the use of magic strings, and I've never been happy with the various workarounds available. They either affect performance or require a lot of extra developer ceremony (which is no good in big teams). I'd always been hoping that C# would introduce something similar to the "typeof" operator that would help you get the name of the current property (or method) without having to use any slow reflection. Before the "//BUILD/" conference, I had given up on C# 5 bringing in anything useful here. But then I was reading Colin Jack's summary of the //BUILD/ talk on Future directions for C# and Visual Basic, and was particularly interested by the new Caller Info Attributes feature of C# 5. This feature is not in the CTP of VS11 yet, so I can't test it, but I expect you'll be able to write the following RaisePropertyChanged method:
protected void RaisePropertyChanged([CallerMemberName] string member = "")
{
    var copy = PropertyChanged;
    if(copy != null)
    {
        copy(new PropertyChangedEventArgs(this, member));
    }
}
and now when you call this method from a property setter, leaving out the optional parameter:
public string UserName
{
    get
    {
        return _userName;
    }
    set
    {
        _userName=value;
        RaisePropertyChanged();
    }
}
the compiler will fill out the parameter for you, passing "UserName" to the RaisePropertyChanged method. What I like about this is that the compiler is creating the magic string for you on every compile - so when you rename your property, the string is automatically kept in sync. This is the best of both worlds, we get the performance benefits of a hardcoded string literal, while keeping everything DRY (and therefore hard to inadvertently break).  
 
22 Comments

Posted in .Net, WPF