C # method call

Possible duplicate:
How to find the method that called the current method?

Hi, how can I define the calling method from a method? For example:

SomeNamespace.SomeClass.SomeMethod() {
   OtherClass();
}

OtherClass() {
   // Here I would like to able to know that the caller is SomeNamespace.SomeClass.SomeMethod
}

thanks

+3
source share
3 answers

These articles should help:

Basically the code is as follows:

StackFrame frame = new StackFrame(1);
MethodBase method = frame.GetMethod();
message = String.Format("{0}.{1} : {2}",
method.DeclaringType.FullName, method.Name, message);
Console.WriteLine(message);
+6
source

You need to use the StackTrace class.

Snippet from MSDN

// skip the current frame, load source information if available 
StackTrace st = new StackTrace(new StackFrame(1, true)) 
Console.WriteLine(" Stack trace built with next level frame: {0}",
  st.ToString());
+1
source

System.Diagnostics.StackTrace:

  StackTrace stackTrace = new StackTrace();           // get call stack
  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

  // write call stack method names
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
  }
+1

Source: https://habr.com/ru/post/1713209/


All Articles