How should I construct Expression tree for string.IndexOf("substring", StringComparison.OrdinalIgnoreCase)
?
I can get it working without the second argument: StringComparison.OrdinalIgnoreCase
. These are my attempts so far:
var methodCall = typeof (string).GetMethod("IndexOf", new[] {typeof (string)});
Expression[] parms = new Expression[]{right, Expression.Constant("StringComparison.OrdinalIgnoreCase", typeof (Enum))};
var exp = Expression.Call(left, methodCall, parms);
return exp;
Also tried this:
var methodCall = typeof (string).GetMethod(method, new[] {typeof (string)});
Expression[] parms = new Expression[]{right, Expression.Parameter(typeof(Enum) , "StringComparison.OrdinalIgnoreCase")};
var exp = Expression.Call(left, methodCall, parms);
return exp;
Please remember that I can get it working if I ignore the OrdinalIgnoreCase
parameter.
Thanks
I suspect there are two problems.
The first is the way you're getting the method - you're asking for a method with only a single string parameter, instead of one with two parameters:
The second is the value you're giving - it should be the actual value of the constant, not a string:
EDIT: Here's a complete working sample:
I didn't check the rest of it, but if only the enum poses problems:
or
And you have more options. Or check my answer here.
Edit: forgot paranthesis.
The simplest way to do it would be to get it via a lambda like this:
This is much more readable and maintainable than manually building an expression tree.
I'm constantly surprised by the amount of people who dive straight into manually building expression trees. There's no need to when you can get the compiler to do the work for you.