Home > C# > C# 5.0 – Caller Information

C# 5.0 – Caller Information

Caller information is introduced in C# 5. This feature is directly available in Visual Studio 2012. As the name suggests, caller information is a set of attributes which can be used to obtain information about caller to a method.

Attributes include, path of the source code, line number, and the member name of the caller. This information is vital in case of debugging or tracing application issues.

CallerFilePathAttribute – String type attribute, this will provide the file path at compile time.

CallerLineNumberAttribute – Integer type attribute, this will provide the line number at which the method is invoked.

CallerMemberNameAttribute – String type attribute, this will provide the Method/Property name of the caller.

Caller information attributes can be specified only to optional parameters. We should also specify a default value. Below example show a typical logging method

//...
Log("Log this");
//...
public void Log(string messageToLog,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string filePath = "",
        [CallerLineNumber] int lineNumber = 0)
{
    //Log the details
}

To make this working, we should include following using statements

using System.Runtime.CompilerServices 
using System.Diagnostics;
Advertisements
Categories: C# Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: