Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identical case condition

I am converting some VB.NET code to C#, as I am more comfortable with it and it helps me in resolving issues faster. However, I came across this code which is NOT an error in VB.NET — but converting it to C# is generating a compiler error.

VB.NET Code

Select Case name
    Case "FSTF"
    .....
    Case "FSTF"
    .....
End Select

C# Converted Code

switch(name) {
    case "FSTF":
        ....;
        break;
    case "FSTF":
        ....;
        break;
}

And the error is:

The Label 'case "FSTF":' already occurs in this switch statement.

What is the solution here — does it mean that in the VB.NET code, the second case statement was just a dummy — or was the first case a dummy?

like image 475
Sekhar Avatar asked Aug 11 '11 18:08

Sekhar


2 Answers

From the documentation for Select...Case:

If testexpression matches an expressionlist clause in more than one Case clause, only the statements following the first match run.

So here the second case is effectively redundant. Personally I prefer the C# approach of highlighting what was almost certainly an unnoticed programming error rather than the deliberate introduction of a duplicate case...

like image 196
Jon Skeet Avatar answered Sep 18 '22 01:09

Jon Skeet


I assume it was done this way to make VB.NET compatible with the Visual Basic 6.0 and older versions because that is the way they behaved. Had VB.NET reported a compilation error like C# then it would have been more difficult to port older Visual Basic code to VB.NET.

The odd thing about this is that VB.NET does not seem smart enough to eliminate the redundant case in the generated CIL code. This leads to another peculiar difference between C# and VB.NET. That is, VB.NET does not change its strategy from a sequential lookup to a Dictionary lookup when targeting string types like C#. This means VB.NET's Select constructs using string types can be slower to execute than C#'s switch counterpart. The reason for this (credit given to MarkJ) is because C# case statements can only contain constants whereas Visual Basic case statements can contain expressions.

like image 36
Brian Gideon Avatar answered Sep 19 '22 01:09

Brian Gideon