Problem solve Get help with specific problems with your technologies, process and projects.

Usage of AndAlso and OrElse

This quick tip will tell VB .NET to use AndAlso and OrElse when when performing an If statement.

This tip was submitted to the tip exchange by member SV Raja. Please let others know how useful it is via the rating scale at the end of the tip. Do you have a useful Visual Basic, .NET or Visual Studio tip or code to share? Submit it to our monthly tip contest.

Use AndAlso and OrElse instead of just AND or OR. When performing an If statement in VB.NET, VB actually evaluates both expressions to see if the who expression is true. Even when the first expression is false, it continues to look at the second argument even though it doesn't have to. This is very helpful when using Functions as expressions in the statement.

Instead of doing this
If(Function1() And Function2()) Then

Do this
If(Function1() AndAlso Function2()) Then

The first code will evaluate the result of Function2(), even if Function1() returned false.
The second will only evaluate Function2() if Function1() returned true.

Do you have comments on this tip? Let us know.

Dig Deeper on .NET Framework 2.0 and Visual Studio 2005 development

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.