HowTo: determine which object (and method) called another method
By rickvdbosch
- 1 minutes read - 183 wordsSometimes 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;
<p>
StackFrame stackFrame;<br /> stackFrame = GetCallingStackFrame();<br /> methodName = stackFrame.GetMethod().DeclaringType.Name;<br /> methodName += </font><font color="#800080" size="2">"."</font><font size="2"> + stackFrame.GetMethod().Name;</p>
<p>
</font><font color="#0000ff" size="2"> return</font><font size="2"> methodName; <br /> }</p>
<p>
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 😉</font></font>
</p>