The C# ECMA Spec shows that (14.11 - Conditional Logic operators):

"* The operation x || y corresponds to the operation x | y, except that y is
evaluated only if x is false."

This is also known as "short-circuit" evaluation, and is also a feature of
C++.

Hope this helps
Brian Johnson


-----Original Message-----
From: Stefan Holdermans [mailto:[EMAIL PROTECTED]]
Sent: 14 June 2002 08:57
To: [EMAIL PROTECTED]
Subject: [ADVANCED-DOTNET] Evaluation of boolean expressions.


I really like the way C# handles boolean expressions like:

    a && b

and

    c || d.

If a is false, b is not evaluated, since the expression cannot be satisfied
anyway; if c is true, d is not evaluated.

But -- is this just a Microsoft-specific implementation of the && and ||
operators? Or do the specifications demand all C# implementations to handle
boolean expressions like this?

E.g., is it safe to code:

    void foo(string bar) {
        if (bar != null && bar.Length > 3) {
            ...
        } else {
            ...
        }
    }

or would a C# implementation be allowed to throw me a NullReferenceException
if bar is a null reference?

(VB6 would throw you an error, since it actually does always evaluate the
second subexpression, indifferent from what the first subexpression
evaluated to. One can argue that the second subexpression should always be
evaluates since it may be a method that, besides returning a boolean,
incorparates some side-effects... but arent't those side-effects bad
practice anyway ;)?)

--Stefan

You can read messages from the Advanced DOTNET archive, unsubscribe from
Advanced DOTNET, or subscribe to other DevelopMentor lists at
http://discuss.develop.com.

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to