Tuesday, November 07, 2006

Get Function Name within Function

I wanted to find the function name of the currently executing line of code, particularly when writing log file from my application. I always found it pretty lame to hardcode the same.

Fortunately, .Net provide classes for this purpose. The StackFrame class enables us to do it. A StackFrame is created and pushed on the call stack for every function call made during the execution of a thread.

Following code shows a demo of the same.

public void ShowMyName()
{
System.Diagnostics.StackFrame objStackFrame = new System.Diagnostics.StackFrame();
MessageBox.Show(objStackFrame.GetMethod().Name);
}