Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the method that called the current method?

When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods.

like image 248
flipdoubt Avatar asked Oct 05 '08 13:10

flipdoubt


People also ask

How can I find the method that called the current method Java?

Getting Name of Current Method inside a method in JavagetEnclosingMethod() returns a Method object representing the immediately enclosing method of the underlying class. StackTraceElement. getMethodName()-The java. lang.

How do you find the method name in a method?

Method Class | getName() Method in Java Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Return Value: It returns the name of the method, as String.

How do you get a name of a method being executed?

More specifically, we can use StackFrame. getMethodName() to find the method name.

How do you call a method in C#?

Calling a method is like accessing a field. After the object name (if you're calling an instance method) or the type name (if you're calling a static method), add a period, the name of the method, and parentheses. Arguments are listed within the parentheses and are separated by commas.


2 Answers

Try this:

using System.Diagnostics; // Get call stack StackTrace stackTrace = new StackTrace();  // Get calling method name Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name); 

one-liner:

(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name 

It is from Get Calling Method using Reflection [C#].

like image 96
Firas Assaad Avatar answered Nov 01 '22 12:11

Firas Assaad


In C# 5, you can get that information using caller info:

//using System.Runtime.CompilerServices; public void SendError(string Message, [CallerMemberName] string callerName = "")  {      Console.WriteLine(callerName + "called me.");  }  

You can also get the [CallerFilePath] and [CallerLineNumber].

like image 35
Coincoin Avatar answered Nov 01 '22 11:11

Coincoin