Search code examples
c#delegatesmethodinfo

Getting method name from an Action delegate


I'm trying to get the method name passed into an Action delegate. This is what I have:

private static void DoAction(params Action<Group>[] actions)
{
    foreach (Action<Group> action in actions)
    {
        Console.WriteLine(action.Method.Name);
    }
}

And in main, this is how it gets called:

DoAction(y => y.DoBar(), z => z.DoFoo());

After the execution of DoAction() method I was hoping to see "DoFoo" and "DoBar" on the screen, but it instead I see <Main>b__0 and <Main>b__1. I was just wondering if there's a way to get the actual name of the target method from an action delegate? Any help is appreciated.


Solution

  • You can change the input type to an Expression and then see if the expression is a method call:

    private static void DoAction(params Expression<Action<Group>>[] actions)
    {
        foreach (var exp in actions)
        {
            var method = exp.Body as MethodCallExpression;
            if(method != null)
                Console.WriteLine(method.Method.Name);
    
            // similar method for properties
            var member = exp.Body as MemberExpression;
            if (member != null)
                Console.WriteLine(member.Member);
    
            // execute the Action
            Action<Group> act = exp.Compile();
    
            Group g = new Group();  // create a Group to act on
            act(g);  // perform the action
    
        }
    
    }