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++)?
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With