CallerMemberNameAttribute

Once very cool feature of .NET 4.5 which passed me by until now is the CallerMemberNameAttribute. Whilst using Reactive UI on a project I accidentally started using an overload of RaiseAndSetIfChanged without the first param being of the form x=> x.PropertyName. Yet the application compiled and seemed to work fine.When I realised my mistake I took a look at the source for ReactiveUI and noticed the use of the [CallerMemberName] attribute on the last argument of the method.

Have a read of the CallerMemberNameAttribute documentation for further info. But basically you can have a string as an optional param with the CallerMemberNameAttribute declaration preceding it and the called method can now find the name of the method that called it. Plus other attributes in CallerFilePathAttribute and CallerLineNumberAttribute which the called method can even get the file path of he source and line number of the where the method was called from. See Caller Information for more.

This is very useful (as shown by it’s use in ReactiveUI) as instead of passing a string from a property for an OnPropertyChanged event with the possibility of typos etc. we can instead let the compiler services handle this using the CallerMemberNameAttribute

public string MyProperty
{
   get { return myProperty; }
   set
   {
      if(myPropery != value)
      {
         myProperty = value;
         //OnPropertyChanged("MyProperty"); -- Replaced
         OnPropertyChanged();
      }
   }
}

private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
   // raise a property changed even or whatever with the propertyName string
}