How to identify the calling method of a method

  • Thread starter Thread starter Rakehs
  • Start date Start date
R

Rakehs

Hi,

I have a method Show() which is invoked by several
methods at different intervals. I want to identify the
calling method within Show() whenever it is invoked. How
do i do this?

Thanks in advance
Rakesh
 
Hi Rakesh,

Actually, you can't for sure.
The only way would be inspecting the stack as Vijaye noted.
However, it takes a lot of time and it isn't reliable because of code
optimizations.
 
But when I use the StackFrame.GetMethod().Name property,
this returns the method i am in and not the calling
method...
 
As Miha pointed out, there may be code optimizations that would give you
different results. Some functions could be completely optimized out and may
never appear in a call stack. But the following code should work fine on a
Debug build (with no optimizations)

This is how you get the full stack trace. (Note: The following code is
taken from MSDN - have not tried it myself.)

// Create a StackTrace that captures
// filename, line number and column
// information, for the current thread.
StackTrace st = new StackTrace(true);
for(int i =0; i< st.FrameCount; i++ )
{
// High up the call stack, there is only one stack frame
StackFrame sf = st.GetFrame(i);
Console.WriteLine("\nHigh Up the Call Stack, Method: {0}",
sf.GetMethod() );
}
 
Hi Alvin,

No, AFAIK there isn't other way than inspecting the stack.
Maybe there is a better approach to your problem (or Rakesh's).
 
Hi Rakehs

Can you tell us why you need to do this? It goes against the normal OO
principle that a class method should never know about its caller -
especially if the caller is a descendent.

Like any rule, there are exceptions. Maybe if you could expand on your
requirements the NG could come up with a more elegant solution.

Regards

Ron
 
Back
Top