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 m
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
.