Denis
Denis

Reputation: 12087

Strange Case Statement in VB.NET with =

Found this code in one of our classes but I am not understanding what the first case statement is doing: "Case i = 1". I am sure that someone just incorrectly converted this from an IF/ELSE statement but why is VB.NET allowing this syntax. What does it mean when it is written this way?

    Dim i As Integer = 1
    Select Case i
        Case i = 1
            Return True
        Case Else
            Return False
    End Select

Upvotes: 2

Views: 820

Answers (6)

Guffa
Guffa

Reputation: 700552

The Case statement can take any expression that is implicitly convertible to the type of the value in the Select statement.

The expression i = 1 will be evaluated to either True or False, which is then converted to an integer value and compared to i.

The integer value of True is -1, so i = 1 will never be equal to i. The case will never be used, regardless of the value of i.

Upvotes: 5

PdotWang
PdotWang

Reputation: 147

It may be a bug. It should be,

Dim i As Integer = 1
 Select Case True
     Case i = 1
         Return True
     Case Else
         Return False
 End Select 

Upvotes: -1

JaredPar
JaredPar

Reputation: 755121

In short the code is effectively doing the following

If i = (i = 1) Then
  Return True
Else
  Return False
End If

The Case expression in a VB.Net Select .. Case statement comes in 3 different forms.

  1. Case expr1 To expr2
  2. Case Is comparisonOp expr
  3. Case expr

This example is the 3rd version of the Case operator. Implicitly the compiler will evaluate the expression testExpr = expr for that Case statement. In this case (haha) it comes out to i = (i = 1)

Note: When run the conditional will actually evaluate to false and hence the else block will be run. The reason why is the expression is actually evaluated as

i = CInt(i = 1)

The i = 1 portion will evaluate to True and due to legacy reasons from VB6 (and COM's version of TRUE) the CInt(True) portion will evaluate to -1 and hence the comparison will fail.

Upvotes: 4

shahkalpesh
shahkalpesh

Reputation: 33474

Use Option Strict and you will see compilation errors.
The code posted above does implicit conversion from integer to boolean & the result will be False.

EDIT: Your code will become
if 1 = (i = 1) then
to
if 1 = (true) then

Upvotes: 1

Dasupalouie
Dasupalouie

Reputation: 7

I think = is an overload operator in vb

it's further discussed here: vb = operator

Upvotes: -1

Andy Finkenstadt
Andy Finkenstadt

Reputation: 3587

shrug Ours is not to reason why, ours is just to simplify.

Return True

Upvotes: -1

Related Questions