Blog Home  Home Feed your aggregator (RSS 2.0)  
What did you learn today? - AndAlso / OrElse
Phil Denoncourt's Technology Rants
 
 Wednesday, March 10, 2004
AndAlso / OrElse by Phil Denoncourt

I've been a VB developer since version 2.0.  Everytime a new version of VB comes out, I skim the “What's New” section of the documentation and then begin using it.

Something that has escaped my scrutiny is two new operators that were added in VB.NET: AndAlso / OrElse

These are related to the And / Or operators, but work a little differently.  Consider the following routine that checks to see if data was returned from a method:

Dim obj As DataSet

obj = GetMeADataSet()

If Not (obj Is Nothing) Then

    If obj.Tables.Count > 0 Then

        If obj.Tables(0).Rows.cout > 0 Then

            'Check out the data

        End If

     End If

End If

It would easier to write the statement as:

Dim obj As DataSet

obj = GetMeADataSet()

If Not (obj Is Nothing) And obj.Tables.Count > 0 And obj.Tables(0).Rows.Count > 0 Then

    'Check out the data

End If

Unfortunately, this statement will fail if obj is nothing or there are no tables in the dataset.  Why?   Because VB will execute all three parts of the if statement, resolve them to boolean values and then perform the boolean math with the AND operator.

The AndAlso operator, has a “short circuiting mechanism“.  As soon as it encounters a false value, it know that the IF statement will not be true, so it either goes to the ELSE section or leaves the if statement.  The opposite is true for the OrElse operator.  As soon as a true condition is found, VB knows that the final result will be true, so it jumps into the IF statement.

So the statement can be rewritten as follow and it will not fail:

 Dim obj As DataSet

obj = GetMeADataSet()

If Not (obj Is Nothing) AndAlso obj.Tables.Count > 0 Andalso obj.Tables(0).Rows.Count > 0 Then

    'Check out the data

End If

Frankly, I don't know why anyone would continue to use the And / Or operators anymore. 

Wednesday, March 10, 2004 12:14:00 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]    | 
Comments are closed.
Copyright © 2008 Phil Denoncourt III. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: