1

I have a structure like below:

public class BaseClass
{
    public string SendError(string Message){

         //which method called me

         return Message;

    }
}


public class TypeAClass : BaseClass
{
    public static TypeAClass Instance { get; set;}

    public void TestToTest()
    {
         SendError("Test Message");
    }
}

Can I get the method name that calls the SendError() in the SendError method. For example, in this scenario it should give me the name TestToTest()

Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105
  • possible duplicate of [How can I find the method that called the current method?](http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method) – M.Babcock Mar 08 '12 at 16:51
  • 1
    Pay attention to the caveats of using StackFrame.GetMethod, as described in [this comment](http://stackoverflow.com/a/172015/832377)... specially inline optimizations. – Mike Mar 08 '12 at 16:59

4 Answers4

9

This is a feature of C# 5:

You can declare a parameter of a function as a caller info:

public string SendError(string Message, [CallerMemberName] string callerName = "")
{
    Console.WriteLine(callerName + "called me.");
}
Coincoin
  • 27,880
  • 7
  • 55
  • 76
2

Try this

StackTrace stackTrace = new StackTrace();
String callingMethodName = stackTrace.GetFrame(1).GetMethod().Name;
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
2
StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(0);
string methodName = caller.GetMethod().Name;
Steve Danner
  • 21,818
  • 7
  • 41
  • 51
0

From the answer of the duplicate question:

using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();

// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

Or more brief:

new StackTrace().GetFrame(1).GetMethod().Name
Community
  • 1
  • 1
M.Babcock
  • 18,753
  • 6
  • 54
  • 84