views:

870

answers:

2

For the following If-statements in VB.NET, what will be the sequence in which the conditions will be evaluated?

Case 1:

If ( condition1 AND condition2 AND condition3 )
.
.
End If

Case 2:

If ( condition1 OR condition2 OR condition3 )
.
.
End If

Case 3:

If ( condition1 OR condition2 AND condition3  OR condition4)
.
.
End If
+5  A: 

VB.Net evaluates all the conditions, so the order isn't important here.

If you want to use short-circuiting, use the AndAlso and OrElse keywords.

Gerrie Schenck
The order could theoretically be important, for example: if IsStatusOkAndIfNotChangePropertyX(MyObject) or PropertyXHasValueN(MyObject) then ...
splattne
It could be but I don't know if you can count on it.
Gerrie Schenck
There's also the 'OrElse' keyword....
Mitch Wheat
+2  A: 

VB.NET is a very strange beast from the C-programmer standpoint. Ass Gerrie mentioned, all three conditions are evaluated in their full entirety without short-circuiting. AndAlso and OrElse can save your day if that's what you want.

As for the last if, the order of evaluation is as follows:

If ((condition1 OR (condition2 AND condition3))  OR condition4)

As a rule of thumb: if there's any ambiguitiy, use brackets to specify order of evaluation explicitly.

Anton Gogolev