Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Name of Action/Func Delegate

Tags:

c#

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?

like image 488
Adam Avatar asked Sep 29 '09 23:09

Adam


2 Answers

You can get the name of the method call by making the parameter an expression instead of a delegate, just like Jon mentioned

private T Get<T>(T task, Expression<Action<T>> method) where T : class {     if (method.Body.NodeType == ExpressionType.Call)     {         var info = (MethodCallExpression)method.Body;         var name = info.Method.Name; // Will return "Bark"     }      //..... } 
like image 45
Rohan West Avatar answered Oct 07 '22 14:10

Rohan West


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.

like image 60
Jon Skeet Avatar answered Oct 07 '22 13:10

Jon Skeet