How do I get the calling method name and type using reflection? [duplicate]

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let’s say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be “Call” and type will be “Caller”.

UPDATE: Two years later since I’m still getting upvotes on this

In .NET 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute.

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); // Output will be the name of the calling method
    }
}

Leave a Comment