Get Name of Action/Func Delegate

c#

Solution

It's giving you the name of the method which is the action of the delegate. That just happens to be implemented using a lambda expression.

You've currently got a delegate which in turn calls Bark. If you want to use `Bark` directly, you'll need to create an open delegate for the `Bark` method, which may not be terribly straightforward. That's assuming you actually want to call it. If you don't need to call it, or you know that it will be called on the first argument anyway, you could use:

private T Get<T>(T task, Action method) where T : class
{
   string methodName = method.Method.Name //Should return Bark
}

private void MakeDogBark()
{
   dog = Get(dog, dog.Bark);
}

You could get round this by making the parameter an expression tree instead of a delegate, but then it would only work if the lambda expression were just a method call anyway.

Problem

I have a weird situation where I need to get the Name of the delegate as a string. I have a generic method that looks like this. ``` private T Get<T>(T task, Action<T> method) where T : class { string methodName = method.Method.Name //Should return Bark } ``` and I am calling it like this ``` private void MakeDogBark() { dog = Get(dog, x=>x.Bark()); } ``` But instead of seeing "Bark" I see this `"<MakeDogBark>b__19"`. So it looks like it is giving me the method name that made the initial call instead of the name of the delegate. Anyone know how to do this?

Original source