Categories
.net

Select Case ambiguity in VB.Net

Consider this piece of code:

Dim a As Integer = 0 Select Case a Case 0 Console.WriteLine("a") Case 0 Console.WriteLine("b") End Select Console.ReadLine()

As a C# developer I was pretty sure that this code will never get compiled. Of course I was wrong. I leave to you guessing which line gets executed.

Does this relaxed compilation makes sense to you? You don’t even get a warning of a clear error in your Select Case. Imagine you have bigger Select Case with a lot of Case lines. You can overlook ambiguity pretty quickly and your application will behave oddly. If you ask me, this feature is just calling for troubles.

If you wonder – C# won’t compile such code ever and this is the only right way of dealing with this issue. You’ll get pretty descriptive error on second case label:

Error 1 The label ‘case 0:’ already occurs in this switch statement …\Projects\WindowsApplication22\Form3.cs 22 22 WindowsApplication22

Compile time errors are best way to find the errors. Far better than your customers finding them.

6 replies on “Select Case ambiguity in VB.Net”

My philosophic approach would be hovever in favour of VB option. SELECT…CASE does not appear to me as math… exclusive function. Therefore.. leave it up to developer

Well, yeah, this is the problem with VB – not being strict. What good does having two possible outcomes out of same input is beyond me – it might just mislead you and it eventually will.

Leave a Reply