Short-circuit conditionals in VB.NET

I’m in a situation now where I am required to write programming code in VB.NET. Which brings me up to a simple programming construct that I came upon by writing code like I would in C#, but getting a different expected result in VB.NET. In C#, using the && operator in conditionals is *by default* a short-circuit type conditional. That means when the first term is evaluated, the additional statements won’t be processed at all if that first statement was not true.

The main benefit is something like this:
Say, you want to check a listbox for specific values…
if(lb1.selectedIndex > -1 && lb1.selectedValue.compare(“value text”) == true)
{ code to run }

If the list box has no list items in there (eg. a selectedIndex of -1), the second condition will never be checked. If C# did not short circuit after the first term resulted in false, a program error would occur because the second condition would not have anything set for the selectedValue property.

Oddly enough, in VB, the And operator is not short-circuited, so I came upon an error due to how I wrote my conditional. I found out with a web search that I need to use the AndAlso operator instead.

Edit: I should also mention OrElse. This, of course, is the short circuited Or version. An example would be:

If Session("val") Is Nothing OrElse Session("val") = String.Empty Then
'code here...
End If

As you can see there, the or can be useful to check if something is empty before continuing…


Posted

in

by