Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the name of the calling function in C#?

Tags:

c#

I need to get the name of the calling function in C#. I read about stackframe method but everywhere its said its not reliable and hurts the performance.

But I need it for production use. I am writing a custom tracer which will be logging the name of the method from which trace was called as well.

Could someone please help with a efficient method to get the calling function name? I am using Visual Studio 2010.

like image 623
shobhit Avatar asked Nov 28 '22 14:11

shobhit


2 Answers

upgrade to c# 5 and use CallerMemberName

public void Method([CallerMemberName] string caller="")
{
}

EDIT

Other nice things with c# 5

public void Method([CallerMemberName] string name="",
                   [CallerLineNumber] int line=-1,
                   [CallerFilePath] string path="")
{
}
like image 107
L.B Avatar answered Dec 06 '22 03:12

L.B


You can do something like:

 var stackTrace = new StackTrace();
 var name = stackTrace.GetFrame(1).GetMethod().Name;

and it work with any version of the framework/language.

like image 24
Felice Pollano Avatar answered Dec 06 '22 04:12

Felice Pollano