C# 5 calling method name – say goodbye to Stackframe hello compilerservices

Posted: 2013-10-03 in .Net

In a previous post of mine I was super excited about using the stackframe for log tracing of calling methods stackframe

I’d now like to fast forward to c# 5.0 System.Runtime.CompilerServices

Using the compiler service we can skip the expense stackframe opperation and simply use optional parameters

So we now simply have:

//using compiler servers to get method name, file and line number

public static void WriteDebug(string message, [CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFileName = "", [CallerLineNumber] int callerLineNumber = 0)
Console.WriteLine("{0} {1} ({2} - {3}) - {4}", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss:fff"), callerMemberName, callerFileName, callerLineNumber, message);

But there is a slight problem, calling method name currently doesn’t support the calling class name. In fairness the below code’s output doesn’t look so great from parallel and static class calls.

//previous stack frame example
public static void WriteDebug(string message)
StackFrame debugginInfo = new StackFrame(1);
string methodName = debugginInfo.GetMethod().ReflectedType.Name + "." + debugginInfo.GetMethod().Name;
Console.WriteLine("{0} {1} - {2}", DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss:fff"), methodName, message);



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