The new .NET 4.5 feature every XAML developer will love

If you develop using XAML and you are using .NET 4.5 (i.e., WPF or Windows 8), then there is a feature that will make you smile a bit: _CallerMemberName_.

XAML developers often implement INotifyPropertyChanged to enable updating of data-bound fields. If you're smart, you often wrap the raising of the event into a simple method you can call—for example:

public void RaisePropertyChange(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

This leads to code that looks like this:

private int ticks;

public int Ticks
{
    get { return ticks; }
    set
    {
        if (ticks != value)
        {
            ticks = value;
            RaisePropertyChange("Ticks");
        }
    }
}

There are some problems with this:

  1. Refactoring – If you rename the Ticks property, even using the VS refactoring tool, it won’t find the string in the method call.
  2. Magic strings – It’s just a string, so there’s nothing to ensure that you spelled "Ticks" in the string the same as in the property name.
  3. Copy & Paste – If you copy & paste another property, you must remember to rename this string too.

The Solution: CallerMemberName

.NET 4.5 includes a new parameter attribute called System.Runtime.CompilerServices.CallerMemberName, which will automatically place the name of the calling member (i.e., method or property) into the parameter. This enables us to change the method signature to:

public void RaisePropertyChange([CallerMemberName] string propertyName = "")

Note: The attribute is applied to the parameter, and we’ve also given it a default value—when using this attribute, your parameter must have a default value.

Now we can change the calling definition to:

private int ticks;

public int Ticks
{
    get { return ticks; }
    set
    {
        if (ticks != value)
        {
            ticks = value;
            RaisePropertyChange(); // No argument needed
        }
    }
}

Now we’ve solved all the problems with the string in the method call! Go and enjoy!

Attachments