Caller Information in .NET 4.5

I was not much interested so far in new features of .NET 4.5. But I did install Visual Studio 2012 RC and so when I have it, I use it for writing a small application for my own needs. And by coincidence, I came across a new feature that I must share.

.NET 4.5 comes with three new attributes that help you to get information about the code that called the current method. You simply declare an optional parameter of an appropriate type, add one of these attributes and the runtime will take care of filling the value.

It’s about these attributes:

CallerFilePathAttribute – name of the source file with path
CallerLineNumberAttribute – line number
CallerMemberNameAttribute – name of the calling member (variable, property etc.)

The usage looks like this:

void Test([CallerLineNumber] lineNumber = 0) {}

It may be useful for diagnostics, logging and so on, but there is also another, quite often scenario when it comes handy (and how I ran into it).

In older versions of .NET framework, the implementation of INotifyPropertyChanged interface (used for data binding in Windows Forms and WPF) requires a parameter with the name of the changed property:

// Declaration
private void NotifyPropertyChanged(string propertyName) {}
 
// Usage
public string Name
{
    set
    {
        if (name != value)
        {
            name = value;
            NotifyPropertyChanged("Name");
        }
    }
}

The name of the property is given to the called method as text, which is obviously not verified by compiler and so it’s easy to make an error.

Alternative implementations exist – for example, with some effort you can specify the property by a lambda expression (see here). Nevertheless the implementation with help of CallerMemberNameAttribute in .NET 4.5 is really straightforward:

private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") {}
 
public string Name
{
    set
    {
        if (name != value)
        {
            name = value;
            NotifyPropertyChanged();
        }
    }
}

It’s all documented on MSDN, so you can easily find details. You just have to know that something like this exists.