Checking out Jouni Heikniemi’s excellent map of What’s new in .NET 4.5 I spotted this comment:

Methods can access call site info as parameter (CallerInfo)

Intrigued, some google-fu revealed that Anders Hejlberg demoed this in his session at build - new attributes [CallerFilePath], [CallerLineNumber] and [CallerMemberName], available for use on method parameters and automatically filled in by the compiler.

The immediate use that springs to mind is for the implementation of the INotifyPropertyChanged interface:

public string Name
{
    get { return mName; }
    set {
        if (!Equals(mName, value)) {
            mName = value;
            OnNotifyPropertyChanged();
        }
    }
}

protected void OnNotifyPropertyChanged(
    [CallerMemberName] string propertyName = "")
{
    ... 
}

Note how we no longer need to pass the name of the property as a magic string to OnNotifyPropertyChanged() because the compiler will fill it in for us.

I’m sure there’ll be more inventive uses though …

Comments

blog comments powered by Disqus
Next Post
A story about Magic  10 Dec 2011
Prior Post
NUnit to the Rescue  01 Dec 2011
Related Posts
Modifying Words, Part the Second  16 Nov 2019
Modifying Words, Part the First  09 Nov 2019
Hashcodes  26 Oct 2019
Code Gardening  19 Oct 2019
Nullable types redux  12 Oct 2019
C# 8 and .NET Core 3.0  28 Sep 2019
Commands and CommandBinding  21 Sep 2019
Debugging word selection  14 Sep 2019
ViewModel Subscriptions  31 Aug 2019
Redux Subscriptions  25 Aug 2019
More csharp posts »
Archives
December 2011
2011