12

I'm trying to figure out of if there is a simple syntax for converting a Method Group to an expression. It seems easy enough with lambdas, but it doesn't translate to methods:

Given

public delegate int FuncIntInt(int x);

all of the below are valid:

Func<int, int> func1 = x => x;
FuncIntInt del1 = x => x;
Expression<Func<int, int>> funcExpr1 = x => x;
Expression<FuncIntInt> delExpr1 = x => x;

But if i try the same with an instance method, it breaks down at the Expressions:

Foo foo = new Foo();
Func<int, int> func2 = foo.AFuncIntInt;
FuncIntInt del2 = foo.AFuncIntInt;
Expression<Func<int, int>> funcExpr2 = foo.AFuncIntInt; // does not compile
Expression<FuncIntInt> delExpr2 = foo.AFuncIntInt;      //does not compile

Both of the last two fail to compile with "Cannot convert method group 'AFuncIntInt' to non-delegate type 'System.Linq.Expressions.Expression<...>'. Did you intend to invoke the method?"

So is there a good syntax for capturing a method grou in an expression?

thanks, arne

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106

3 Answers3

10

How about this?

  Expression<Func<int, int>> funcExpr2 = (pArg) => foo.AFuncIntInt(pArg);
  Expression<FuncIntInt> delExpr2 = (pArg) => foo.AFuncIntInt(pArg);
Vasu Balakrishnan
  • 1,751
  • 10
  • 15
  • 2
    Did you ever find a nicer syntax for this one? I don't completely understand why the compiler can't figure out the method group of an Expression> when it can figure it out for Func.. – skrebbel May 31 '11 at 12:34
  • My assumption is that foo.AFuncIntInt is a methodgroup, not an expression and there are no automatic conversions from methodgroup to expression, however there is automatic conversion to accept a lambda as either a methodgroup or an expression – Arne Claassen May 31 '11 at 15:48
1

It is also possible to do it using NJection.LambdaConverter a Delegate to LambdaExpression converter Library

public class Program
{
    private static void Main(string[] args) {
       var lambda = Lambda.TransformMethodTo<Func<string, int>>()
                          .From(() => Parse)
                          .ToLambda();            
    }   

    public static int Parse(string value) {
       return int.Parse(value)
    } 
}
Sagi
  • 8,972
  • 3
  • 33
  • 41
0

I use property instead of method.

public class MathLibrary
{
    public Expression<Func<int, int>> AddOne {  
        get {   return input => input + 1;} 
    }
}

Using above

enter image description here

Rm558
  • 4,621
  • 3
  • 38
  • 43