Nick
Nick

Reputation: 988

Detecting statically whether a linq expression is null

My problem is that I want to check for any given Linq Expression, say whether it is as an expression equal to the expression constant null (i.e. Expression.Constant(null)), without compiling it. However, what I don't want to do is compare whether the value of the expressions is null. This is a purely syntactic check. For example, this expression would not work:

Expression.Equal(Expression.Constant(null), a) for expression a

Since

Expression.Equal(Expression.Constant(null), 
           Expression.Conditional(
                  Expression.Constant(false),
                  Expression.Convert(Expression.Constant(3), typeof(object)),
                  Expression.Constant(null)))

would evaluate to true, which is not what I'm looking for.

I want to do it ideally with something like a.IsNullExpr. However, the naïve solution of doing

public static bool IsNullExpr(Expressions a) { return a == Expression.Constant(null); }

doesn't seem to work, presumably because the equality operator for linq expressions is done based on the object address (or something similar) (I think, at the very least Expression.Constant(null) == Expression.Constant(null) evaluates to false).

Is there a very simple way of solving this problem which I've overlooked?

Upvotes: 2

Views: 102

Answers (1)

Evk
Evk

Reputation: 101483

If I understand you correctly, you can do it like this:

Expression exp = Expression.Constant(null);
bool isNull = exp is ConstantExpression && ((ConstantExpression)exp).Value == null;

Upvotes: 3

Related Questions