Reputation: 5817
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()
Upvotes: 1
Views: 2155
Reputation: 18965
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
Upvotes: 0
Reputation: 22158
StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(0);
string methodName = caller.GetMethod().Name;
Upvotes: 2
Reputation: 28596
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.");
}
Upvotes: 9
Reputation: 30097
Try this
StackTrace stackTrace = new StackTrace();
String callingMethodName = stackTrace.GetFrame(1).GetMethod().Name;
Upvotes: 2