Geeks With Blogs
CodeSeeker Just another developer trying to do the right thing

In-line checking of values during the evaluation of a compound IF statement in VB.NET can be done as a way of "short-circuiting" the IF statement in case further evaluation might cause errors. For example,
Dim blah As Nullable(Of Integer) = Nothing
If blah.HasValue And blah.Value < 5 Then
    Console.WriteLine("Something really important")
End If
In this case, the IF statement will cause an error. The AND operator in VB causes all clauses prior to the THEN statement to be evaluated. So both the "blah.HasValue" and "blah.Value < 5" clauses will be evaluated. "blah.HasValue" is false but evaluation continues to the next clause. Then "blah.Value < 5" causes a "System.InvalidOperationException: Nullable object must have a value."

There are two ways to deal with this situation. One is with a nested IF statement, like this:
Dim blah As Nullable(Of Integer) = Nothing
If blah.HasValue Then
    If blah.Value < 5 Then
         Console.WriteLine( _
             "Something really important")
     End If
End If
In this case, the second IF statement will not be evaluated if the first IF statement does not pass.

Another, more elegant way to deal with this situation is to use the VB.NET AndAlso operator. With this operator, the IF statement does not go on to the next clause if the first clause is not true; in effect "short-circuiting" the IF statement.
Dim blah As Nullable(Of Integer) = Nothing
If blah.HasValue AndAlso blah.Value < 5 Then
    Console.WriteLine("Something really important")
End If
Now, the second clause of the IF statement will not be evaluated because the first clause returned False, and an exception will not occur. Posted on Monday, July 23, 2007 9:03 AM | Back to top

Copyright © Mike Ellis | Powered by: GeeksWithBlogs.net