VB.net’s Not Commonly Use But Handy Short-Circuiting Logical Operator

As a programmer, always get to fix bugs and adding in feature in existing program, well this happen to most of all new programmer. Every program have and should have logical operation, which using IF AND ELSE operator. In VB, there is a handy operator provided, but I have not seen it in all those codes I’m taking over from previous project, and myself not even using it until not long ago, and it is handy.

The short-circuiting logical operator AndAlso and OrElse, it serve the same purpose as normal And and Or, but it skip the following condition check if the first one does not meet the condition.
For real life example I’ve face recently, considering a field in database is suppose to contain int value, but it can be Nullable, so, on the front end, we would like to get or maybe convert the value to string and do something with it, so basically it will go like this

[cc lang=”vbnet” escaped=”true”]
If Not myDataReader.IsDBNull(0) And myDataReader.GetString(0) “” Then
‘ Do something here
End If
[/cc]

note that this statement will cause exception, where the value is Null . Because when using And, it will check all the statement before deciding whether to execute or not. It could have be better with this:

[cc lang=”vbnet” escaped=”true”]
If Not myDataReader.IsDBNull(0) AndAlso myDataReader.GetString(0) “” Then
‘Do something here
End If
[/cc]

By using AndAlso, the second statement will be skipped if the first statement is false, which mean it save time, and prevented exception in this case. The same goes to OrElse. 🙂