2

When using OR with an if statement does the computer check both statements if the first statement returns true?

bool a = true;
            bool b = LongComplicatedMethod();

            if (a || b)
            {
                Console.WriteLine("Hello");
            }

So say the boolean b has its value determined by a long complicated algorithmic method, would the method for b be called if a was true?

3
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by DaveTran
1

No, || and && will short circuit. In an ||, if the left hand side evaluates to true, there is no need to evaluate the right hand side. Similarly, if the left evaluates to false in an &&, the right also becomes a useless check. As such, each will short circuit and skip the right side. See section 7.11 of the language specification.

With this, code like the below is legal

Foo foo = null;
if (foo != null && foo.Equals(someOtherFoo))
{
    // do something 
}

Without short-circuiting, the right side of the conditional would throw a NullReferenceException. In the present reality, the left side evaluates to false and the right side is never checked.

0

That's cool. Thanks for the info.

Is this the same with most languages you have encountered or just C# specific?

1

It varies from language to language. For example, And and Or do not short circuit in VB. This code is the presumed equivalent of the C# code I presented, but you get the NullReferenceException due to the check on the right side.

Dim foo As Foo = Nothing
Dim someOtherFoo As Foo = New Foo()

If Not (foo Is Nothing) And foo.Equals(someOtherFoo) Then

End If

In order to get a short circuiting behavior in VB, you would use AndAlso and OrElse to skip the right side if the left side renders it moot.

Edited by apegram: n/a

Votes + Comments
expert knowledge
0

Yes, that's a language specific thing. And you have to make yourself clear weather logical expressions are short-circuited or fully evaluated. That is a one thing that causes some hard to track errors when porting an application from one language to another.

VB.NET has also logical short-circuit operators, namely AndAlso and OrElse.

0

Excellent thanks guys, I've added this info to my list of code tips.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.