08 Sep 2012

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 are 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 – rename the Ticks property and even if you use the VS refactoring tool it won’t find the string in the method call.
  2. Magic strings – It is just a string so there is nothing to make sure that you spelt Ticks in the string the same as Ticks 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 in front of the property & note we have 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();
        }
    }
}

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

Below is a file with a sample application to get you started (everything is in MainPage.xaml.cs).

AttachmentSize
Package icon demo.zip21.69 KB

Comments

Dew Drop – September 10, 2012 (#1,397) | Alvin Ash's picture

[...] The new .NET 4.5 feature every XAML developer will love (Robert MacLean) [...]

Interesting .NET Links - September 10 , 2012 | TechBlog's picture

[...] The new .NET 4.5 feature every XAML developer will love – Robert MacLean [...]

Links of the day– 11 September 2012 « Va's picture

[...] The new .NET 4.5 feature every XAML developer will love [...]

Links of the day – 11 September 2012 « V's picture

[...] The new .NET 4.5 feature every XAML developer will love [...]

Add new comment