1

I have a main method, ExecuteMethod, in C# which is in charge of executing the method passed as a parameter. Now I would like to make a log to a file in order to know which method is being executed every time (I am only interested in getting the method name):

    public static void ExecuteMethod(Action myMethod)
    {
        ExecuteMethod(() => { myMethod(); return true; });
    }

    public static object ExecuteMethod(Func<object> myMethod)
    {
        string myMethodName = <method_name>; // How to extract method name here from myMethod parameter?
        MyLog.Write("Calling to " + myMethodName);

        // more stuff here
    }

So for example, in my program I have calls like below:

    public void m1()
    {
        ExecuteMethod(() => myCore.SomeMethod1(param1, param2));
    }

    public void m2()
    {
        ExecuteMethod(() => myCore.SomeMethod2(param1, param2, null));
    }

Then from above ExecuteMethod, I would like to obtain the names of these methods passed as parameter which would be SomeMethod1 and SomeMethod2 in this case. How can I achieve this?

Willy
  • 9,848
  • 22
  • 141
  • 284
  • 2
    [`[CallerMemberName]`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute?view=net-6.0)? – canton7 Jan 07 '22 at 14:57
  • @canton7 It seems using [CallerMemberName] is returning in my case method names m1 and m2 instead of SomeMethod1 and SomeMethod2 respectively. – Willy Jan 07 '22 at 16:48

1 Answers1

1

A quick look at the Action properties revealed Action.Method.Name, but the name it reports is a run-time construct that doesn't say much. In your case it would probably report something like <m1>b__2_0.

You could work around this by passing the name of the method with the call to ExecuteMethod:

ExecuteMethod(() => myCore.SomeMethod1(param1, param2), nameof(myCore.SomeMethod1));

And using that:

public static object ExecuteMethod(Func<object> myMethod, string methodName)
{        
    MyLog.Write("Calling to " + methodName);

    // more stuff here
}
oerkelens
  • 5,053
  • 1
  • 22
  • 29