Friday, January 22, 2010

Finding the name of current method and your calling method (C#)

Hi, sometimes we need to know the name of the current method or better the calling method ( i need this to put that in the log) So the easiest way to get the name of the current method is
MethodInfo.GetCurrentMethod().Name.
But if you need to know the name of your calling method?
Easy:)

// Jump up the stack frame one level and locate the  calling method.
StackFrame stackFrame = new StackFrame(1); //the "1" one level up
 MethodBase callingMethod = stackFrame.GetMethod();
// Build a string containing the namespace and method name
string caller = callingMethod.DeclaringType.FullName + '.' + callingMethod.Name;

That's it:)
Very Easy in .net Framework

No comments:

Post a Comment