Tuesday, December 11, 2012

INotifyPropertyChanged without explicitly using the property Name


public class MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _message;
    public string Message
    {
        get { return _message; }
        set
        {
            if (_message != value)
            {
               _message = value;
               OnPropertyChanged("Message");
           }
        }
    }

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

All of you, Silverlight and WPF developers, recognize this code. You have dozen of those properties that call the “OnPropertyChanged” method with hardcoded property name.
Some of you perhaps solved this problem using lambda expressions or some other ways.
In this post I’d like to show you another cool way to avoid hardcoding your properties name every time you call “OnPropertyChanged”.

private void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

You: Huh?
Me: Exactly!

Let me introduce you to the “CallerMemberName” attribute that allows you to obtain the method or property name of the caller to the method.
If the Message property calls the “OnPropertyChanged” method, the propertyName default parameter will be automatically set with the calling property name in compile time, meaning that the property name will be hardcoded inside the dll.
The only catch here is that in order to use this attribute the parameter has to be default.
    public string Message
    {
        get { return _message; }
        set
        {
            if (_message != value)
            {
               _message = value;
               OnPropertyChanged();
           }
        }
    }

FYI
There’re more attributes with abilities like CallerMemberName, such as:
CallerFilePath – gives you the source file path
CallerLineNumber – returns the line number of the calling method 

  
Type safe ;)

2 comments:

  1. awesome. always hated that piece of code

    ReplyDelete
  2. Find this feature while using Resharper. Very neat. However, this feature is available on framework above 4.0 if I'm not mistaken.

    ReplyDelete