Or versus OrElse

前端 未结 8 1576
感情败类
感情败类 2020-11-27 04:33

What\'s the difference between or and OrElse?

if temp is dbnull.value or temp = 0

produces the error:

相关标签:
8条回答
  • 2020-11-27 04:59

    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.

    0 讨论(0)
  • 2020-11-27 05:04

    The reason the compilation fails in the example is the order of operations.

    The expression parser is trying to evaluate "dbnull.value or temp" first.

    if temp is (dbnull.value or temp) = 0
    

    The error is here, because you can't do a bitwise OR between an integer (temp) and dbnull.value.

    OrElse fixes this, not because it's short-circuited, but because it's lower on the order of operations, and so "temp is dbnull.value" and "3=0" are being evaluated first, rather than the parser trying to compare dbNull and temp.

    So the evaluation with OrElse works like you're expecting: (assume temp=3)

    if temp is dbnull.value OrElse temp = 0 then
    if 3 is dbnull.value OrElse 3 = 0 then
    if false OrElse 3=0 then
    if false OrElse false then
    if false then
    

    This was actually on an entry exam at a software company I used to work for, and it was a common problem I used to encounter in VB6. So it's a good idea to parenthesize your sub-expressions when using boolean operators:

    This would have compiled properly:

    if (temp is dbnull.value) Or (temp = 0) then 
    

    Although, as everyone has already pointed out, OrElse and AndAlso are really the correct operators to use in this context.

    0 讨论(0)
提交回复
热议问题