Wednesday 21 February 2007

C# Lazy or full boolean evaluation?

C# allows for both full and lazy evaluation. For full evaluation use the single operators for And/Or (|/&), for lazy evaluation use the double operators for And/Or (&&/||).
e.g.
Full Evaluation
if ((sName==null) | (sName="~empty~"))
...do something

will cause an exception if sName is null as the second comparions (="~empty~") will be performed.

Lazy Evaluation
if ((sName==null) || (sName="~empty~"))
...do something

will not cause an exception if sName is null because as the rest of the expression is an OR the result will be true irrespective of the rest of the expression, and so the rest of the expression is ignored.