Obtaining Method Caller Information in C#

A method can now obtain information about the method that called it.
Well, as of .NET 4.5 / Visual Studio 2012 this is possible!

Usage

A method can obtain the following information about its caller:

  • Member name
  • Source file path
  • Line number

To get this information all we need to do is define optional parameters and decorate them with an attribute from the System.Runtime.CompilerServices namespace. The compiler will do the rest.

Let’s see an example:

public static void Log(string msg, 
    [CallerMemberName] string memberName  = "", 
    [CallerFilePath] string filePath = "", 
    [CallerLineNumber] int lineNumber = 0)
{
    string msgToLog = string.Format("{0} ({1} line {2}): {3}",
        memberName, filePath, lineNumber, msg);
    Trace.WriteLine(msgToLog);
}

The simple Logger class above defines a single method – Log. The method accepts four parameters, the first of which is the message to be logged and the rest will automatically receive caller information.

Now let’s use our logger:

class BusinessLogic
{
    public void PerformLogic()
    {
        // do logic
        Logger.Log("Finished performing logic.");
    }
}

As you can see, when we invoke the logger we only have to provide a value for the first parameter – the message. The rest of the parameters are automatically provided values by the compiler. The output when the above method executes will be similar to the following:

PerformLogic (c:\Project\Program.cs line 26): Finished performing logic.

To summarize, here is how we obtain caller information:

  • To obtain the member name, define an optional parameter of type string and decorate it with theCallerMemberName attribute
  • To obtain the source file path, define an optional parameter of type string and decorate it with theCallerFilePath attribute
  • To obtain the line number, define an optional parameter of type int and decorate it with theCallerLineNumber attribute

The order of the above parameters is insignificant and we aren’t required to define all of them.

An Alternative to Caller Information (and why it isn’t as good)

This feature is new to .NET 4.5 / Visual Studio 2012. If you’re using a previous version, you need to find an alternative. You can use the System.Diagnostics.StackFrame class to obtain information about the calling method at runtime. Consider this revised Log method:

public static void Log(string msg)
{
    StackFrame stackFrame = new StackFrame(1);
    string methodName = stackFrame.GetMethod().Name;
    string fileName = stackFrame.GetFileName();
    int lineNumber = stackFrame.GetFileLineNumber();

    string msgToLog = string.Format("{0} ({1} line {2}): {3}",
        methodName, fileName, lineNumber, msg);
    System.Diagnostics.Trace.WriteLine(msgToLog);
}

Here we instantiate a StackFrame and provide it with a value of 1, to get information about the method one frame up the call stack. We then use it to extract the method name, file name and line number.

 

Advertisements
By Sriramjithendra Posted in C#.NET

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