Order of evaluation in an If statement

  • Thread starter Thread starter Victory
  • Start date Start date
V

Victory

Hi,
I am running into a problem which is best described with an example:

Dim aList as ArrayList = Nothing
...
if (aList IsNot Nothing) And (aList.Count > 0) then
....

This always gives me an exception. I have also tried switching the order
like:

if (aList.Count > 0) And (aList IsNot Nothing) then
...
and i get the same thing. I have had to break this into separate if
statements. Can anyone shed a light on this and explain why this does
not work?
thanks,
Mars
 
Hi,
I am running into a problem which is best described with an example:

Dim aList as ArrayList = Nothing
..
if (aList IsNot Nothing) And (aList.Count > 0) then
...

This always gives me an exception. I have also tried switching the order
like:

if (aList.Count > 0) And (aList IsNot Nothing) then
..
and i get the same thing. I have had to break this into separate if
statements. Can anyone shed a light on this and explain why this does
not work?
thanks,
Mars

If (aList IsNot Nothing) AndAlso (aList.Count > 0) Then

Use AndAlso instead of And. And and Or evaluate all parts of the
expression, AndAlso and OrElse stop evaluating when the final result
is known. Use And and Or only for logical operations on numeric
values.

Be aware that Iif works the same way - all arguments are always
evaluated.
 
Close!

AndAlso stops evaluating when the expression(s) to the left evaluates to
False.

OrElse stops evaluating when the expression(s) to the left evaluates to
True.
 
I am surprised. And works this way in C#, C and C++ so what required
this change in VB .NET?
Thank you both!
Mars.
 
Simple answer = VB was never based or derived from C/C++, it was based on
BASIC.

The AndAlso and OrElse operators were added in VB.Net 2003 to provide
exactly that 'short-circuiting' behaviour.
 
Victory said:
I am surprised. And works this way in C#, C and C++ so what required
this change in VB .NET?

Actually there is no operator named 'and' in C#, C, and C++, respectively.
However, C# has both '&' and '&&' operators, which share semantics with VB's
'And' and 'AndAlso' operators. '|' maps to 'Or' and '||' maps to 'OrElse'.
 
Back
Top