Best way to check if value is null in Expression Tree

c# expression-trees

Question

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));
1
2
7/10/2015 8:47:38 AM

Accepted Answer

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.

http://tryroslyn.azurewebsites.net/#f:r/K4Zwlgdg5gBAygTxAFwKYFsDcAoUlaIoYB0AMpAI7ECiAHgA4BOqI4A9hCDvcAEYA2YAMYwh/AIasYAYRgBvbDCUweA4TABubMABMYAWQAUASnmLlFukxbsIAHgBiwCELspG+AHyeY4mAF4YEwCfACJQmAB+SJhwnAsAX2wEoAA=

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.

3
7/10/2015 9:24:02 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow