What is the best way to check if constant is null in Expression Trees?
// Method to call (Regex.IsMatch)
MethodInfo isMatchMethod = typeof(Regex).GetMethod("IsMatch", new[] { typeof(string), typeof(string), typeof(RegexOptions) });
// The member you want to evaluate: (x => x.<property_name>)
var member = Expression.Property(param, propertyName);
// The value you want to evaluate
var constant = Expression.Convert(Expression.Constant(value), type);
// How to check if constant is null???
var expr = Expression.Call(isMatchMethod, member, constant, Expression.Constant(RegexOptions.IgnoreCase));
// Doesn't work
// Expression notNullConstant = value != null ? constant : Expression.Convert(Expression.Constant(string.Empty), type);
//var expr = Expression.Call(isMatchMethod, member, notNullConstant, Expression.Constant(RegexOptions.IgnoreCase));
Not sure what the problem is. You can translate a ?? b
literally into a tree with Expression.Coalesce
. If in doubt compile an expression with the C# compiler and look at what it did.
Meanwhile you have asked how to compile ?:
. The answer is the same: Simply decompile existing code to see what is being output. Use Expression.Condition
.