Search code examples
c#.net-corec#-4.0expression-trees

How to pass StartsWith() as a parameter to Expression.Call()?


Im trying to call StartsWith() function as an expression and pass a constant to it.

var textConstant =Expression.Constant(text);
var startsWith = Expression.Call(StartsWith ,textConstant); //something like this

Im new to c# and I couldn't figure out how to pass these into Expression.Call().


Solution

  • Here is sample:

     string text = "Some string";
     string startsText = "Some";
            
     Expression callExpr = Expression.Call(
                              Expression.Constant(text), 
                              typeof(String).GetMethod("StartsWith", 
                                             new Type[] { typeof(String) }),
                              Expression.Constant(startsText));
            
     // print the expression
     Console.WriteLine(callExpr);
            
     // execute the expression
     var lambda = Expression.Lambda<Func<bool>>(callExpr).Compile();
     Console.WriteLine(lambda());