Back to all posts

Visual Studio 11 Caller Member Info Attributes

Posted on Feb 29, 2012

Posted in category:
Development
C#

If you have been paying attention to what is going on in the Microsoft Community today you will notice is a big day. Visual Studio 11 Beta, as well as Windows 8 Consumer Preview, were both released this morning, for those of us developers it means tons of new tools to try out and lots of new functionality that we can use in our applications as well as productivity and language improvements with.NET 4.5. With this, I'm starting a new blog series highlighting some of the new items that I find helpful, cool, or otherwise interesting with VS 11 Development. Today's installment talks about Caller Member Info Attributes.

Caller Member Attributes What are They?

Caller Member Attributes are as the name implies attributes that you can add to get information about the caller. There are currently three attributes supported in VS 11 per the beta that was released today.

  • [CallerMemberName] - Replaces the parameter value with the name of the calling member
  • [CallerFilePath] - Replaces the parameter value with the calling file path
  • [CallerLineNumber] - Replaces the parameter value with the calling file line number

Now before you get worried that this type of behavior might add runtime performance concerns it is important to note that this replacement is done at Compile Time. (This is already demoed in the Metro Style application templates).

Where/How to Use?

So sure, this is great in all, but where and how can I use this? Well, the usage is pretty simple and I think there are a lot of great places to use this type of structure. One example would be to add to every log message details on the caller. For example, you could do the following.

Example Using Caller Member Attributes
public static void LogMessage(string Message,
    [CallerMemberName] string member = string.empty,
    [CallerFilePath] string filePath = string.empty,
    [CallerLineNumber] int lineNumber = 0)
{
        //Do your stuff here
}

Notice the use of optional parameters. You can simply call this using LogMessage("My Message") and when it actually logs the message the other values will come across automatically for you. This is a great use. Another great usage would be to use [CallerMemberName] to implement a single "Notify" method for raising the PropertyChanged event when implementing INotifyPropertyChanged.

Conclusion

Although a simple thing, I think that these additions to the language will prove very helpful. Especially for those of us working on the framework/foundation things. Feel free to share your comments below.