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.
ApiController.cs
public class ApiController
{
public void GetMethod()
{
OtherMethod();
}
}
OtherClass.cs
public class OtherClass()
{
public void OtherMethod()
{
Console.WriteLine(/*I want to get the value 'ApiController' to print out*/)
}
}
What I've tried:
- I've looked at How can I find the method that called the current method? and the answers will get me the calling method (OtherMethod) but not the class (ApiController) which has that method
- I tried
[CallerMemberName]
and usingStackTrace
properties but these don't get me the method's class name
So it can be done like this,
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 callingStackFrame.GetMethod()
, and then you use theDeclaringType
property of theMethodInfo
to get the type in which the method is defined, which isApiController
.You can achieve this by below code
First you need to add namespace
using System.Diagnostics;
The instance of
stackTrace
is depend upon your implementation environment. you may defined it locally or globallyOR
You may use below method without creating
StackTrace
instanceTry this may it help you
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)Why not simply pass the name as constructor parameter? This doesn't hide the dependency, unlike
StackFrame
/StackTrace
.For example: