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
In short the code is effectively doing the following
The
Caseexpression in a VB.NetSelect .. Casestatement comes in 3 different forms.This example is the 3rd version of the
Caseoperator. Implicitly the compiler will evaluate the expressiontestExpr = exprfor thatCasestatement. In this case (haha) it comes out toi = (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 = 1portion will evaluate toTrueand due to legacy reasons from VB6 (and COM’s version ofTRUE) theCInt(True)portion will evaluate to-1and hence the comparison will fail.