Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Method Am I In?

I am aiming to add some #if DEBUG to my methods however I don't want to edit the code I copy and Paste into each method.

Is there a generic piece of code like this:

void DoSomething()
            {
#if Debug
            Log("Now In " + MethodName);
#endif
            }

Where MethodName is populated to equal DoSomething, or whichever Method called the Log?

like image 251
Dave Gordon Avatar asked Apr 16 '26 20:04

Dave Gordon


1 Answers

If you're using .NET 4.5 you can use the CallerMemberName attribute:

public static GetCallerMemberName([CallerMemberName]string caller = null)
{
    return caller;
}

Note that when calling this method you don't need to pass anything as an argument - the C# compiler does the work for you. This also means that you avoid performing reflection at runtime, which makes this method much faster.

Usage:

void DoSomething()
{
#if Debug
    Log("Now In " + GetCallerMemberName()); // Logs "Now in DoSomething"
#endif
}
like image 100
Adi Lester Avatar answered Apr 18 '26 10:04

Adi Lester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!