OrElse
and AndAlso
are two new logical operators in VB .NET and they have some properties that can enhance your codes in two general categories:1. Avoid executing part of a logical expression.
2. Optimize code by not executing any more of a compound expression than required.
OrElse
and AndAlso
are quite similar with the And
and Or
except that VB .NET supports short-circuiting with the OrElse
and AndAlso
operators. This means that the expressions will only be executed when necessary. Anyway, the And
and Or
are still present in VB .NET.For example:
// Assume that str1 = 5,
// x = 1 and y = 1
If x > str1 And y < str1 Then
' code
End If
When performing an
And
operator in VB .NET, it actually evaluates both of the expressions to get the final outcome. Even the first condition (x greater than str1
) returns as FALSE
, it still continues to look at the second argument even though it doesn’t need to.Let’s see how
AndAlso
evaluates the codes below.If x > str1 AndAlso y < str1 Then
' code
End If
When using
AndAlso
, VB .NET knows that the expression will not succeed once it is determined that the first condition (x greater than str1
) is FALSE
. So it stops evaluating the expression right away without checking the second condition.The difference of
Or
and OrElse
are also similar to And
and AndAlso
operator, which Or
will check all the conditions and OrElse
won’t checking the remaining expression, if it found any of the previous condition is TRUE
.
0 comments:
Post a Comment