This blog is moved to

Thursday, June 25, 2009

Getting calling method name in C# using Reflection

The name of the calling method can be extracted from the stack. Since the method on top of the stack is the method that is currently being executed, the calling method will be right below it. Thus, by instantiating StackTrace and getting the frame with index 1 will result in getting a StackFrame that corresponds to the call from the calling method. Finally, reflection can be used to get method name.
using System.Diagnostics;

void Log(string eventMessage)
Console.WriteLine("Event logged by " + (new StackTrace()).GetFrame(1).GetMethod().Name);
Console.WriteLine("Event: " + eventMessage);


No comments: