Today I’ve encountered a strange problem running expressions – I wanted to created an expression tree that looks something like this:
(e) => e.Owner != null && e.Owner.ID = 4455
So I’ve used the Expression.MakeBinary method to create a binary expression and passed it an ExpressionType.And enum, thinking this is the C# “&&” operator.
When running the expression on an e instance that had no owner (null), I got an exception. When looking at the created expression it looked something like this:
(e) => e.Owner != null AND e.Owner.ID = 4455
At first I didn’t notice any difference (I just thought the ToString() created an easy-to-read string), but after comparing it with the same expression written by hand with a lambda expression, I noticed the difference between the “AND” operator and the “&&” operator.
As it turns out, ExpressionType.Add is actually a bit-wise operator (similiar to &) and the enum that matches the && operator is the ExpressionType.AndAlso (the && operator is what is called a short-circut evaluator).
This is the same with the || (or) operator – the ExpressionType.Or is the bitwise or, whilst the ExpressionType.OrElse is the actual “||” operator.
I honestly think that it would have been better if they named this types as ExpressionType.BitwiseAnd and ExpressionType.And – makes more sense, doesn’t it?
So be careful the next time you want to use and/or in your expression tree.