2

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));
Vitone
  • 498
  • 1
  • 7
  • 19
  • Any reason you're not using `Expression.Constant(value, type)`? Is it not actually a constant of that type? Can you give us more background? – Jon Skeet Jul 10 '15 at 08:54
  • Did you have a look at this answer? http://stackoverflow.com/a/18795667/26396 – Enrico Campidoglio Jul 10 '15 at 08:57
  • What do you mean, "doesn't work"? Also, what are you actually trying to do? You're not actually testing for null *in an expression tree*, so your question is a bit confusing. – Luaan Jul 10 '15 at 08:57
  • I want to get something like this using Expression Trees: Regex.IsMatch(property, pattern ?? string.Empty, RegexOptions.IgnoreCase) – Vitone Jul 10 '15 at 09:12
  • @Dzienny, thanks, good idea! But I am using converting, so in my case this variant is better: Regex.IsMatch(property, value != null ? pattern : string.Empty, RegexOptions.IgnoreCase). How to write **?:** operation? – Vitone Jul 10 '15 at 09:20
  • 3
    Well, there's `Expression.Condition` for the ternary operator `?:`. Although, I'd suggest `Expression.Coalesce` anyway. – Dzienny Jul 10 '15 at 09:23

1 Answers1

3

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.

usr
  • 168,620
  • 35
  • 240
  • 369