What none of the other respondents has pointed out is that the C# switch
statement is limited to numeric values, including members of
enumerations,
in the switch argument (not just numeric constants or enumeration
members).
VB's Select Case statement offers the useful ability to use string
variables
or string constants in its Case statements, but C# does not support an
equivalent other than a series of if / else if / else if statements. Too
bad, because it's not uncommon to want to do something like that.
It's not even uncommon in C#, where System.String _is_ in fact a supported
type for a switch/case statement. No one else pointed out the lack of
support for that in C#, because it's not entirely true.
It's true that a case statement cannot have a variable; it has to be a
compile-time constant. And that in fact is what's relevant in this
question, I believe. But strings are definitely a supported type.
The net
effect on performance of choosing case statements vs. a series of if
/else
if statements is insignificant, usually.
Hardly. The C# compiler will optimize a switch/case into jump tables or a
dictionary, providing O(1) performance characteristics instead of the O(n)
that if/else would.
Any insignificance would be a result of a very small "n", rather than a
difference in implementation detail. But obviously even for relatively
small "n" (say dozens) there must be a performance improvement, given that
the compiler team saw fit to include such an optimization.
Ironically, there's no way for VB.NET to include an optimization like this
if variables are used in case statements. So even if it has this sort of
optimization normally, it would be disabled in the usage shown in this
topic.
However from a coding style
viewpoint many prefer the structure of a switch/Select Case in situations
where there's more than two or three cases that you want to test. I
wouldn't
surprise me if C# eventually added the capability - the language
developers
are competitive and each has been known to adopt features that the other
language offers.
C# has allowed strings in switch/case since v1.0.
I doubt C# will ever support variables in case statements; it's completely
contrary to the concept of a relatively simple language without hidden
performance traps.
Pete