shobhit
shobhit

Reputation: 89

How can I get the name of the calling function in 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.

Upvotes: 4

Views: 5107

Answers (3)

eFloh
eFloh

Reputation: 2158

You can use the C# 4.5 Attributes mentioned in L.B's answer with .NET 3.5 or above by simply declaring them (you need to compile using vs2012 or higher, else you won't get any error, but the parameter value will stay null!):

namespace System.Runtime.CompilerServices
{
  [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
  public sealed class CallerMemberNameAttribute : Attribute
  {
  }

  [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
  public sealed class CallerFilePathAttribute : Attribute
  {
  }

  [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
  public sealed class CallerLineNumberAttribute : Attribute
  {
  }
}

Upvotes: 9

L.B
L.B

Reputation: 116108

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="")
{
}

Upvotes: 12

Felice Pollano
Felice Pollano

Reputation: 33252

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.

Upvotes: 9

Related Questions