Whats the difference between or and OrElse?
if temp is dbnull.value or temp = 0
produces the error *Operator '=' is not defined for type 'DBNull' and type 'Integer'.**
while this one works like a charm!
if temp is dbnull.value OrElse temp = 0
Whats the difference between or and OrElse?
if temp is dbnull.value or temp = 0
produces the error *Operator '=' is not defined for type 'DBNull' and type 'Integer'.**
while this one works like a charm!
if temp is dbnull.value OrElse temp = 0
(I've looked at other answers and realized I was terribly wrong)
The OrElse operator "performs short-circuiting logical disjunction on two expressions", that is to say: if the left operand is true and so the entire expression is guaranteed to be true the right operand won't even be evaluated (this is useful in cases like:
string a;
//...
if (a is null) or (a = "Hi") //...
to avoid a NullReferenceException throw by the right-hand operand.
I'm sincerely astonished that this (lazy evaluation) isn't the default behaviour of or
and and
as it is in C/C++ and C# (and many other languages...)
OrElse is short circuited, this means that only one side of the expression will be tested if the first side is a match.
Just like AndAlso will only test one side of the expression if the first half is a fail.
OrElse
is a short-circuiting operator, Or
is not.
By the definition of the boolean 'or' operator, if the first term is True then the whole is definitely true - so we don't need to evaluate the second term.
OrElse
knows this, so doesn't try and evaluate temp = 0
once it's established that temp Is DBNull.Value
Or
doesn't know this, and will always attempt to evaluate both terms. When temp Is DBNull.Value
, it can't be compared to zero, so it falls over.
You should use... well, whichever one makes sense.
This is the same behaviour as with C#, where everyone uses the Coditional Or (||) and the Conditional And (&&), where you also have the normal Or (|) and normal And (&). So comparing C# to VB.Net is:
| => Or
|| => OrElse
& => And
&& => AndAlso
The condifitonal boolean operators are very usefull preventing nested if constructions. But sometimes the normal boolean operators are needed to ensure hitting both code paths.