Sometimes when you’re inside a method you would like to know which method called it. Or even which object. For instance when you write a TraceListener, it might be pretty cool to make the TraceListener smart enough to find out what object called him and from which method. The StackTrace object in .Net makes this pretty easy. Here’s a howto…

First, we iterate through the stackframes that are available on the stack, looking for the one we need. This method returns such a StackFrame. We skip the first StackFrame by starting the variable count at 1, because this method is always called from the method GetCallingMethod() (see below).

private StackFrame GetCallingStackFrame()
{
    StackTrace stack;
    StackFrame stackFrame;

    stack = new StackTrace(true);
    // Initialize the StackFrame by creating a default one.
   
stackFrame =
new StackFrame("ErrorDeterminingStackFrame", 0, 0);
    for (int count = 1; count < stack.FrameCount; count++)
    {
        // At my current project I skipped the StackFrame if the calling method was ‘WriteLine’, because that’s the WriteLine method in the TraceListener.
        if
(!stack.GetFrame(count).GetMethod().Name.Equals("WriteLine"))
        {
            stackFrame = stack.GetFrame(count);
            break;
        }
    }
    return stackFrame;
}

Next, we can get our information from the StackFrame. There’s lots of stuff on there, like the method, the filename and even line- and columnnumbers. The method below returns a string containing CallingObject.CallingMethod.

protected
string GetCallingMethod()
{
    string methodName;

    StackFrame stackFrame;
    stackFrame = GetCallingStackFrame();
    methodName = stackFrame.GetMethod().DeclaringType.Name;
    methodName +=
"." + stackFrame.GetMethod().Name;

    return methodName;
}

I know there’s some work in this code when it comes to defensive programming. For instance: who tells me GetMethod() will return anything containing a DeclaringType property. But that’s not the issue in this post 😉