‘Stupid’ Question 12: What is this new attribute [CallerMemberName] in C#?
Sorry for the delayed post, I had the worst migraine of my life yesterday and the only thing I could do was to drink water (thank you Bob Mentzer /
@bobmentzer for the tip) and listen to Hanselman podcasts. But, I’m up and running again - migraine pulsating from time to time, but it is way better than yesterday.
CallerMemberName is one of three new attributes in C#5 called Called Info Attributes.
If you have been reading my WinRT/Metro app posts then you might have noticed that I talk about the Bindable helpclass found in the Metro examples, basically it allows you to implement INotifyPropertyChanged interface in a neater way. What I haven’t done, is explain how the class works. And when I was going to I noticed a new attribute I haven’t paid much attention to, the [CallerMemberName] attribute. It is new, isn’t it? And what is it?
The answer is yes, it is a new feature in C# 5
CallerMemberName is one of three new attributes in C#5 called Called Info Attributes. These attributes tells the compiler to give you information from the caller’s source code. You have to apply the attributes to optional parameters which should have default values defined.
The three attributes are:
CallerFilePathAttribute : File path at compile time.
CallerLineNumberAttribute: Line number in the source file at which the method is called
CallerMemberNameAttribute: Method or property name of the caller
The attributes are quite useful for logging information, and for sorting out magic strings such as the ones we are used to seeing when implementing INotifyPropertyChanged ;)
I’ll make a small demo later this week :)
Last modified on 2012-07-31