This isn't really a problem, but more of a curiosity of mine that I haven't been able to resolve by my own means. I surely won't be losing any sleep over it.
In VB.NET, the switch statement syntax is (as documented on MSDN here):
Select [ Case ] testexpression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Note that in the first line, Case
is in square brackets, meaning that it is optional.
And indeed, the following example compiles and executes in the same way as if the Case
keyword had been included, at least, in the rudimentary examples I've tried:
Select myIntVar
Case 0
Return "Nothing"
Case 1
Return "Just one"
Case Else
Return "Something else"
End Select
Therefore my question is as follows:
Aside from syntax, is there any difference between opening a switch statement with Select
and Select Case
?
I did a small experiment. I made up a small console application like so:
Module Module1
Sub Main()
Dim myStr As String = GetString(1)
End Sub
Private Function GetString(myIntVar) As String
Select myIntVar
Case 0
Return "Nothing"
Case 1
Return "Just one"
Case Else
Return "Something else"
End Select
End Function
End Module
The first run was as pictured above, and then I compiled it again inserting the Case
keyword. I disassembled both created executables using ILDasm
and pasted the IL of the GetString
function into this online diff site: http://www.diffchecker.com/9ef7z423
Looks to me like Select Case
and plain old Select
are purely syntax differences (this is of course excluding the usage of Select
in LINQ queries).
I would say there is no difference between the two forms. However, my only evidence is by way of an absence of drawing any distinction. Rather than looking at the Language Reference, the definitive place to look is in the Language Specification1.
In Version 11, under section 10.8.2, the Select Case statement is discussed, and the syntax shown is:
SelectStatement ::=
Select
[Case
] Expression StatementTerminator
[ CaseStatement+ ]
[ CaseElseStatement ]End Select
StatementTerminator
So, it's clear that this section does cover both forms. However, in the preceding 5 paragraphs (the entirety of the specification for Select Case Statements) no distinction is drawn between the two forms.
1The Reference tries to be descriptive, give examples, and uses (at times) looser language. The Specification should be followable to create a Visual Basic compiler. If something is missing from the former, then it may just be an omission. If something is missing from the latter, then it's not officially part of the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With