Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MethodInfo for a lambda expression

I know I am asking the bizarre but just for kicks, is it possible to get the MethodInfo for a lambda expression?

I am after something like this:

(Func<int, string>(i => i.ToString())).MethodInfo

UPDATE I want to get the method info regardless of whether the body of the lamda is a method call expression or not, i.e. regardless of what type of expression the body of the lambda is.

So, for e.g.

This might work.

var intExpression = Expression.Constant(2);
Expression<Func<int, Dog>> conversionExpression = i => Program.GetNewDog(i);

var convertExpression5 = Expression.ConvertChecked(intExpression, typeof(Dog), ((MethodCallExpression)(conversionExpression.Body)).Method);

class Program
{
  static Dog GetNewDog(int i)
  {
    return new Dog();
  }
}

But I want even this to work:

var intExpression = Expression.Constant(2);
Expression<Func<int, Dog>> conversionExpression = i => new Dog();

var convertExpression5 = Expression.ConvertChecked(intExpression, typeof(Dog), /*...???... */);
like image 676
Water Cooler v2 Avatar asked Jan 06 '15 05:01

Water Cooler v2


2 Answers

You are quite close :)

You can do something like this:

MethodInfo meth = (new Func<int, string>(i => i.ToString())).Method;

Note: This might have problems if you have multiple 'subscribers' to a delegate instance.

Reference: https://learn.microsoft.com/en-us/dotnet/api/system.delegate.method

like image 130
leppie Avatar answered Oct 27 '22 04:10

leppie


Using the System.Linq.Expressions namespace, you can do the following.

Expression<Func<int, string>> expression = i => i.ToString();
MethodInfo method = ((MethodCallExpression)expression.Body).Method;
like image 37
Timothy Shields Avatar answered Oct 27 '22 05:10

Timothy Shields