‘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:
(from MSDN)
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 :)
Comments
They are features of the language. If you define your own attribute named System.Runtime.CompilerServices.CallerMemberNameAttribute, then you can use them on .NET 4.0 or 3.5 as long as you are compiling with the new compiler.
Hi Iris, Your post reminded me a similar post by Pavel Yosepovich that can be found here: http://blogs.microsoft.co.il/blogs/pavely/archive/2012/03/20/inotifypropertychanged-implementation-with-c-5-0.aspx I think you might like his other posts too since he talks about Metro a lot. Pavel is a Microsoft MVP, a great instructor and a very nice person. Have a nice day, Boris
Last modified on 2012-07-31