Using CallerMemberName with INotifyPropertyChanged in C#

In previous post “Callerinfo Attribute In C#” we have seen the CallerInfo attributes helping in debugging the code.

In this post we would see how CallerMemberName attribute is used while using INotifyPropertyChanged interface. For a quick introduction to INotifyPropertyChanged interface click here.

To implement this interface, you need to use the System.ComponentModel namespace.



The following code shows an implementation of the interface. The method RaisePropertyChanged takes single string parameter. The parameter is described as the name of the property. The FirstName property is using the RaisePropertyChanged method and the property name is sent as parameter.


Now, we would use the CallerInfo attribute, for that we need to use the System.Runtime.CompilerService namespace.


The following code shows that, the CallerMemberName attribute is used in the method RaisePropertyChanged. Also notice that, the parameter is made as optional.


The following code shows uses of the RaisePropertyChanged method, where FirstName property is using the method providing the property name and LastName without any parameter.


Both the above mentioned properties are valid. In case you are providing the wrong property name in the parameter, using CallerMemberName it automatically provides the member name if nothing is provided. This implementation is very safe against what we were doing first.


Hope this post is useful.

Thanks for reading. Like Method Of Tried in Facebook.