Think In Geek

In geek we trust

C#, the “and” operators and lazy evaluation

Today at work we found a bug. My workmate, not used to C#, usually uses the & operator to compare boolean values. However, in C#, the & operator does not use lazy evaluation.

One curious thing about C# is that it can use two different operators to calculate an and expression: the & operator and the && operator. The difference between both is that the first one (&) can be used both with integer types and boolean types. When used with integer types it will perform a bitwise comparison between the two, and when used with boolean values it will use the logical and operation between the two boolean values, evaluating all the parts of the expression. This means that using a code like this one:

if (someObject != null & someObject.SomeProperty == someValue)

will throw a runtime error if someObject is null, because it will try to obtain the SomeProperty value.

However, the && operator is only available to boolean expressions, and it uses lazy evaluation, this is, if the first condition evaluated is false, it will calculate false without evaluating the rest of the expression, because an and is only true if all the expressions are true.

Conclusion, be sure to always use &amp& when evaluating boolean values if you want to avoid run time surprises :).

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn


One thought on “C#, the “and” operators and lazy evaluation

  • Vicne says:

    I think your workmate should really learn the meaning of bitwise operations.
    The fact that C# knows both & and && is nothing “Curious”. It’s been so for ages in C, C++, Java and other languages. These are two basically different operators, one is arithmetic and works on numbers seen in their binary form, while the other one is a conditional operator working in boolean values.
    The fact that the single & also works with boolean types is just a side-effect because booleans can be considered numbers with just one binary digit (btw, in C, the language has no “boolean” predefined data type so it is often defined as a synonym of int by a macro).
    So I really think the conclusion is that your workmate should stop using & for && and reserve the single & for binary calculations.
    The same is true for | vs || by the way.
    Best regards,

Leave a Reply

Your email address will not be published. Required fields are marked *