How to get the name of the class which contains the method which called the current method?

  • A+
Category:Languages

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 snippet helps.

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 using StackTrace properties but these don't get me the method's class 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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: