C# pass any method as a parameter

cmethodsparameters

When logging, you always get entangled in string literals.

I solved that nicely for properties, fields and variables by passing an Expression<Func<T>> expression (as explained here), so you can do things like this:

public void Demo(string someArgument)
{
    LogFrameWork.LogLine("Demo"); // goal is to get rid of these string literals
    LogFramework.Log(() => someArgument);
}

I want to do something similar for the method Demo itself:

public void Demo(string someArgument)
{
    LogFramework.Log(this.Demo);
}

I tried things like this:

public static void Log(Delegate method)
{
    string methodName = method.Method.Name;
    LogLine(methodName);
}

and this:

public static void Log(Action method)
{
    string methodName = method.Method.Name;
    LogLine(methodName);
}

But I get compiler errors like these:

Argument 1: cannot convert from 'method group' to 'System.Delegate' 
Argument 1: cannot convert from 'method group' to 'System.Action'   

I could introduce a bunch of overloads using Func<…> and Action<…>, but that sounds overly complex.

Is there a way to cover this for any method with any number of parameters and an optional result?

–jeroen

PS: I think this question might have some relevance here, but no answers that got me a 'aha' feeling 🙂

Best Answer

You can also achieve this without using ExpressionTrees through System.Diagnostics.StackTrace.

StackTrace trace = new StackTrace();

And then:

trace.GetFrame(0).GetMethod().Name

To get the MethodInfo and then name of the current method, or:

trace.GetFrame(1).GetMethod().Name 

To get the calling method.