Convert Method Group to Expression
Asked Answered
B

3

13

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

Britten answered 16/6, 2009 at 21:54 Comment(0)
P
11

How about this?

  Expression<Func<int, int>> funcExpr2 = (pArg) => foo.AFuncIntInt(pArg);
  Expression<FuncIntInt> delExpr2 = (pArg) => foo.AFuncIntInt(pArg);
Phylum answered 16/6, 2009 at 22:1 Comment(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<Func<something>> when it can figure it out for Func<something>..Chantellechanter
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 expressionBritten
S
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)
    } 
}
Sanity answered 21/12, 2013 at 19:19 Comment(0)
A
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

Anesthesia answered 17/3, 2020 at 23:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.