What is the VB.NET select case statement logic with case OR-ing?

后端 未结 5 997
一个人的身影
一个人的身影 2021-02-06 20:42

I\'m using an Or statement in my case expression.

Even though I have a value within this range, it didn\'t find a match. Why not?

Example Code:<

5条回答
  •  再見小時候
    2021-02-06 20:55

    Edit: It appears I was wrong in assuming that VB.NET doesn't allow Case ORing. I was thinking in C# and IL and it appears I was wrong.

    However, as someone pointed out, the reason your code did not work was because Case 2 Or 3 was evaluating 2 Or 3 as a bitwise or and hence evaluating to Case 3.

    For clarification:

    
           2 binary = 0000 0010
           3 binary = 0000 0011
      2 Or 3 binary = 0000 0011 (= 3)
    
    
      Select Case 2
         Case 0            '--> no match
    
         Case 1            '--> no match
    
         Case 2 Or 3       '(equivalent to Case 3  --> no match)
       End Select
    

    However, I feel that I should point out that for the sake of performance, one should not use such constructs. When the compiler encounters Select statements (switch in C#) it will try to compile them using lookup tables and the switch MSIL instruction but in the case where you have something like Case 1,2,11,55 the compiler will not be able to convert that to a lookup table and it will have to use a series of compares (which is like using If.. Else).

    The point is that in order to really take advantage of the Select statement, the cases should be designed with that in mind. Otherwise, the only benefit is code readability.

    A well designed switch is an O(1) operation whereas an poorly designed one (which is equivalent to a series of If..Then..Else statements) is an O(n) operation.

提交回复
热议问题