Chris Roberts

Saving processor time AndAlso writing tidier code, OrElse!

• Posted in Programming

Every once in a while, you stumble across something new and you wonder how you ever survived before you found it. This happened to me most recently when I came across the AndAlso and OrElse operators in VB.NET.

The official description of the AndAlso operator from Microsoft is that it "Performs short-circuiting logical conjunction on two expressions".

What does this mean? The 'logical conjunction on two expressions' means that it basically performs the same task as a standard logical 'And':

Result = P And Q

As you'd expect, Result is only true when both P and Q are true. Conversely, if P is false, Result must be false regardless of the value of Q.

This is where AndAlso comes into play. AndAlso is smart enough to realize that if P is false, there's no point in even evaluating Q. The process of evaluating Q is 'short circuited' as it's a pointless endeavour. This not only saves a little processing time, but it can allow you to refactor your code quite nicely, too. Take this piece of code, for example...

Dim Result As Boolean = False
Dim MyObject As Object

MyObject = SomeFunctionCall

If (Not MyObject Is Nothing) Then
    If (MyObject.Value > 5) Then
        Result = True
    End If
End If

If Result Then
    ' Perform a task
End If

Using AndAlso, this can be refactored to a much tidier version:

Dim MyObject As Object

MyObject = SomeFunctionCall

If (Not MyObject Is Nothing) AndAlso (MyObject.Value > 5) Then
    ' Perform a task
End If

What would happen had you tried to do this with a traditional 'And'? Well - if 'MyObject' were ever 'Nothing' - a runtime exception would have been thrown as the code would also try to evaluate 'MyObject.Value'. But - as we're using 'AndAlso' - when 'MyObject' is nothing, the second expression is completely ignored and everything works as you'd want it to.

OrElse

OrElse works in a similar way, but for a logical disjunction (an 'or' to you and me). With an 'or' statement, the result is true when either of the expressions involved are true. So, if the first expression is true, the second expression never needs to be evaluated (and indeed isn't if you use OrElse).

Personally, I haven't found many uses for OrElse since I found out about it - but AndAlso is now appearing all over my code!