39

I am trying to find ways to log method name in an efficient manner w.r.t. speed and maintainability. I guess, In .NET 4.5 Caller Information attributes are exposed just for this purpose except the speed part. I feel these are just syntactic sugars from using System.Reflection.MethodBase.GetCurrentMethod() or stackTrace.GetFrame(1).GetMethod().Name (Got from here). (or) Are these methods give performance benefits too?

In C#, Is there a way to get method name at compile time (as like in C++)?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Imran
  • 694
  • 5
  • 12
  • 4
    Have you actually profiled their performance, or are you simply pre-empting an issue that may not be an issue? – Daniel Kelley Apr 19 '13 at 09:26
  • @DanielKelley I have not measured the performance. I wanted to know what is happening under the covers of Caller Information attributes. Daniel mentioned that the replacement happens at compile time which is exactly I am looking for. – Imran Apr 19 '13 at 09:33

1 Answers1

89

The caller information attributes cause the C# compiler to supply the caller's name at the callsite. This happens at compile-time, there is no reflection involved.

public void DoProcessing()
{
    LogCall();
}

public void LogCall([CallerMemberName] string memberName = "")
{
     Console.WriteLine(memberName + " was called.");
}

Will be compiled to:

public void DoProcessing()
{
    LogCall("DoProcessing");
}

public void LogCall(string memberName)
{
     Console.WriteLine(memberName + " was called.");
}
Daniel
  • 15,944
  • 2
  • 54
  • 60
  • 2
    This is exactly what I am looking for. Thanks for your quick response. Do you have any idea to achieve the compile time replacement in the older versions of .NET? – Imran Apr 19 '13 at 09:36
  • 1
    [CallerMemberInfo] will work with any .NET version as long as you use the C# 5 compiler. See http://stackoverflow.com/questions/13381917/is-the-callermembername-attribute-in-4-5-able-to-be-faked – Daniel Apr 19 '13 at 09:44
  • Thanks for the link. I am not presently using c# 5 compiler which requires VS2012. – Imran Apr 19 '13 at 09:55