Search code examples
c#reflectionexpression-trees

How to generate an `Expression` reference to a method parameter


If I have a method that is building code using Expression trees, to handle runtime types, how can I make an Expression that references a parameter to the method?

E.g. in the below code, how do I build Expressions to pass in that reference the method parameters?

public static bool ExpressionContains(string s, string sub) {
    var cmi = typeof(String).GetMethod("Contains", new[] { typeof(string) });
    var body = Expression.Call(cmi, s ???, sub ???);

    return Expression.Lambda<Func<bool>>(body).Compile().Invoke();
}

Solution

  • Since the expression compiles to a Func<bool>, as far as it is concerned, the values of s and sub are constants:

    public static bool ExpressionContains(string s, string sub) {
        var cmi = typeof(String).GetMethod("Contains", new[] { typeof(string) });
        var body = Expression.Call(
            Expression.Constant(s),
            cmi,
            Expression.Constant(sub));
    
        return Expression.Lambda<Func<bool>>(body).Compile().Invoke();
    }
    

    If you wanted to compile a Func<string, string, bool> where s and sub were passed in, then:

    public static bool ExpressionContains(string s, string sub) {
        var sExpr = Expression.Parameter(typeof(string), "s");
        var subExpr = Expression.Parameter(typeof(string), "sub");
        var cmi = typeof(String).GetMethod("Contains", new[] { typeof(string) });
        var body = Expression.Call(sExpr, cmi, subExpr);
    
        return Expression.Lambda<Func<string, string, bool>>(body, new[] { sExpr, subExpr }).Compile().Invoke(s, sub);
    }