I have a requirement where I need to know the name of the class (ApiController) which has a method (GetMethod) which is called by another method (OtherMethod) from a different class (OtherClass).
To help explain this, I hope the below pseudo-code snippets help.
public class ApiController
{
public void GetMethod()
{
OtherMethod();
}
}
public class OtherClass()
{
public void OtherMethod()
{
Console.WriteLine(/*I want to get the value 'ApiController' to print out*/)
}
}
What I've tried:
[CallerMemberName]
and using StackTrace
properties but these don't get me the method's class nameThe current method name that contains the execution point that is represented by the current stack trace element is provided by the java. lang. StackTraceElement. getMethodName() method.
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name.
using System.Diagnostics;
var className = new StackFrame(1).GetMethod().DeclaringType.Name;
Goes to the previous level of the Stack, finds the method, and gets the type from the method. This avoids you needing to create a full StackTrace, which is expensive.
You could use FullName
if you want the fully qualified class name.
Edit: fringe cases (to highlight the issues raised in comments below)
async
methods get compiled into a state machine, so again, you may not get what you expect. (Credit: Phil K)So it can be done like this,
new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().DeclaringType.Name
StackFrame represents a method on the call stack, the index 1 gives you the frame that contains the immediate caller of the currently executed method, which is ApiController.GetMethod()
in this example.
Now you have the frame, then you retrieve the MethodInfo
of that frame by calling StackFrame.GetMethod()
, and then you use the DeclaringType
property of the MethodInfo
to get the type in which the method is defined, which is ApiController
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With