5

This is not a duplicate of this question : VB.NET Stacking Select Case Statements together like in Switch C#/Java. The answer provided here does not answer my question. The answer there is stating that there is an automatic break in VB .Net, which I'm aware of. I'm asking if there's any workaround.

In C, it is possible to do something like this :

int i = 1;
switch (i) {
   case 1 :
     //Do first stuff
     break;
   case 2 :
     //Do second stuff
     //Fall Through
   case 3 :
     //Do third stuff 
     break;
}

Basically

  • If i is 1, app will do first stuff.
  • If i is 2, it will do second AND third stuff.
  • If i is 3, it will do only third stuff.

Since there is an auto break at the end of each Select case statement in VB .Net, does anyone know how to achieve this in VB .Net ?

In a nice and pretty way I mean...

Community
  • 1
  • 1
Martin Verjans
  • 4,675
  • 1
  • 21
  • 48

1 Answers1

7

Your premise is wrong. In C# you can't fall through to the next case if the current case has statements. Trying to do so will result in a compilation error.

You can, however, (ab)use goto case to get this working.

switch(0)
{
    case 0:
        Console.WriteLine("0");
        goto case 1;
    case 1:
        Console.WriteLine("1");
        break;

}

VB.Net has no equivalent of goto case

Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351
  • I think the OP mentioned c, not c# although the post has been updated quite a bit so maybe c# was originally mentioned? – Igor May 10 '16 at 14:42
  • @Igor Yes, originally it was C#. – spender May 10 '16 at 14:43
  • Yeah but it's the same concept... I was wondering if there was an equivalent to that in VB .Net... – Martin Verjans May 10 '16 at 14:43
  • By the way - it's worth noticing that `goto case` in C# can jump to any case (upwards too) and has **no safeguards** as seen in [this infinite switch fallback loop](https://dotnetfiddle.net/p4eOGE) – quetzalcoatl May 10 '16 at 14:46
  • @quetzalcoatl No, it really is good old `goto` from our BASIC days with a bit of sugar. – spender May 10 '16 at 14:48
  • Yeah, you're stuck using `goto label` (rather that a more elegant `goto case`). But on the upside, it looks like VB can make a jump table from a `Select Case`: https://social.msdn.microsoft.com/Forums/vstudio/en-US/fe35bbda-2a3b-4ba5-9c85-92d235b7e451/select-case-efficient-code?forum=vbgeneral – rskar May 10 '16 at 14:52
  • what about the infamous `GoTo` Statement??, https://msdn.microsoft.com/en-us/library/69whc95c(v=vs.120).aspx – abichango May 10 '16 at 14:58
  • 2
    The day a goto abuse anwser is a good anwser, hell frozen over. – user6144226 May 10 '16 at 14:59