Safest Way to Use RaisePropertyChanged Method

Background

All the developers working with XAML related apps are very well aware about the use of this RaisePropertyChanged. I am sure, most of us are also aware of where to use this. But does everyone aware about what is the proper way or let's say generic way to use it??? Well, even if you are not aware, no problem. At the end of this post, you will surely take home a useful tip on using RaisePropertyChanged. Before moving forward, I want to make a point clear that this post will be useful only when your requirement is changing frequently leading to frequent change in variable/property names also and compromising a bit on performance is better than having missing data.

Introduction

As we know that MVVM provides a loose coupling methodology. At lot many places it is very useful to get the benefit of such architecture, but at the cost of your alertness. Because when we are talking about MVVM, we usually say that ViewModel has no knowledge about View and properties are the way, who binds View and ViewModel to show the data on the UI. Here is the gotcha!!! ViewModels implement INotifyPropertyChanged interface, so that the property changes in ViewModel can be passed onto View. Let's take a sample property, to understand in better way:

public string SelectedName
{
    get { return _selectedName; }
    set
    {
        if (_selectedName != value)
        {
            _selectedName = value;
            RaisePropertyChanged("SelectedName");
        }
    }
}

Point to note here is the hard coded name of the property "SelectedName" within the RaisePropertyChangedmethod. Now, due to requirement change, one of the developer came and change the name of a property SelectedNamefrom to FirstName, and at the same time, he forgot to change the parameter of  RaisePropertyChanged method.  Now what will happen??? This silly oversight will neither cause any compile or run time errors, but our feature will simply not work. And such things are very difficult to detect until and unless there is a major break in functionality. So, now, how to get rid of such sort of issues???  

Tip comes here

Instead of hard coding the property name, can't we go ahead and fetch the property name dynamically using Reflection APIs. Well, of course we can.  

Reflection.MethodBase.GetCurrentMethod().Name

To implement it in better way, let's go ahead and create an extension method to read this property name as:

public static  string GetPropertyName(this System.Reflection.MethodBase methodBase)
{
    return methodBase.Name.Substring(4);
}

Here Substring method is required to get rid of 'get_' and 'set_' at the start depending upon where it is called.  So, by using this extension method, one will be able to raise property changed events without concern that in future your property name might change. I hope above article is useful.