Select Case ambiguity in VB.Net

Posted by Miha Markič on January 18, 2007 · 2 mins read

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.