ExpressionType.And VS ExpressionType.AndAlso

August 26, 2009


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.

Further links:

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



  1. ShlomoAugust 26, 2009 ב 10:18 pm

    ב – יש את האופרטור And ו – AndAlso שזה בדיוק מה שתיארת כאן

  2. עידוAugust 26, 2009 ב 10:33 pm

    בגלל זה עדיף שמות enum שלא יהיו מקובעים לשפה ספציפית, אלא יהיו מספיק ברורים.

    אגב, אני מחכה לשמוע את ההרצאה שלך מחר, שיהיה בהצלחה.