Introduced in .NET Framework v4.5 (as a C# 5.0 compiler
feature), the CallerMemberNameAttribute allows you to determine the method or
property name of the caller of a method.
This comes in very handy if you’re adding logging code, or in
the case of with WPF you’re using models based on the INotifyPropertyChanged
interface, where you need to fire the PropertyChanged event passing along the
name of the property that’s changed.
Prior to the availability of CallerMemberName, you had a
couple of choices when calling the PropertyChanged event:
- Pass a hard-coded string to identify the property name.
This has clear drawbacks – what if the property name changes/identifying code dependent on the property?
- Parsing an expression tree that represents a concrete class
property
Handy, because you’re referring to a class's property
There are plenty of examples available showing how to parse
an expression tree (see below), but be very careful, parsing an expression tree
is very, very slow compared to using
the CallerMemberName or passing in a string to identify the property.