Fog Creek Software
Discussion Board

Welcome! and rules

Joel on Software

printing the calling method name : C#

In my file - I have a series of methods fa(), fb(), fc() all of them calling logsomething()

in logsomething() I want to print the method that called it - i.e. could fa, fb or fc.

How do I do this?

C# noob
Thursday, April 28, 2005

From the current mehod you can use...


If you don't want to pass the method name to your logging function, you'll have to use StackFrame...

System.Diagnostics.StackFrame stackFrame
    = new System.Diagnostics.StackFrame();

System.Reflection.MethodBase methodBase =

string methodName = methodBase.Name;

Jeff Mastry
Thursday, April 28, 2005

OOPS, that second option should be for StackTrace (not StackFrame):

StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();

The call to GetFrame(1) retrieves the stack frame of the immediate caller.

Jeff Mastry
Thursday, April 28, 2005

Jeff's right.  However, a word of caution: StackTrace can be _very_ slow for some operations.

Thursday, April 28, 2005

Thanks jeff, Fire

The StackTrace portion would be a performance hit I guess, even reflections are exactly performance friendly. If you had to create a logging method that has to log the method name - what would your choice be?

C# noob
Friday, April 29, 2005

I would probably go with MethodBase.GetCurrentMethod because it is easier to read and understand.

If this is for logging exceptions, I wouldn't be too worried about the overhead since exception handling is already pretty slow. If this is for something more, I would consider passing the method name to the logging class.

Jeff Mastry
Friday, April 29, 2005

*  Recent Topics

*  Fog Creek Home