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?

Recommended Answers

All 5 Replies

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.

That's cool. Thanks for the info.

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

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.

commented: expert knowledge +6

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.