Monday 23 April 2012

Dot.Net: Method name Reflection

Question:
How to get the method name of the method you are executing?
I want to log the method name of my context method; how do I do that?


Answer:
Use the StackTrace class, get the first frame, and ask for the method name.
Here is an example
private string GetMethodName()
{
    StackTrace stackTrace = new StackTrace();
    StackFrame stackFrame = stackTrace.GetFrame(1);
    return stackFrame.GetMethod().Name;
}

private void Test()
{
    logger.error("You are in method:" + GetMethodName());
    ...
}





No comments: