Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# switch statement more limited than vb.net 'case' [closed]

I was reading an interesting article here and it made an interesting point about the 'case' statement in vb.net vs the 'switch' statement in C#, which I've pasted below:

The following Visual Basic Select Case statement can't be represented in C# with a single switch statement:

Dim Condition As Integer = 55
Select Case Condition
  Case 1, 3 To 5, 10, 12, 14, Is > 50
    'value 55 executes code here
  Case Else
    'values <1, 2, 6-9, 11, 13, 15-49
End Select

I've always found the switch statement in C#, with dropthrough and consequentrequirements for a break in each case, to be a bit unwieldy. Is there any reason they haven't enhanced the switch command to allow these situations? When would dropthrough be useful anyway? Anyone know of any extensions of the construct to allow more flexibility?

Cheers

like image 258
Glinkot Avatar asked May 04 '11 23:05

Glinkot


2 Answers

In C# you can only use distinct values in cases. This makes it more limited, but on the other hand it makes it faster because it can be implemented using a hash lookup.

The switch syntax has been made more restricted in C# than in C/C++. You can still do the same things, but a fall through is not made implicitly, you have to write a specific jump to the next case. The reason for this restriction is that it's much more common to do fall through by mistake than intentionally.

In C# you would need an if statement in the default case to handle the ranges:

int condition = 55;
switch (condition) {
  case 1:
  case 3:
  case 4:
  case 5:
  case 10:
  case 12:
  case 14:
    // values 1, 3-5, 10, 12, 14
    break;
  default:
    if (condition > 50) {
      // value 55 executes code here
    } else {
      // values <1, 2, 6-9, 11, 13, 15-49
    }
    break;
}
like image 52
Guffa Avatar answered Oct 06 '22 23:10

Guffa


I remember a uni lecturer once telling us the only useful thing he had ever found to do with fall through was write out the lyrics to the twelve days of christmas.

Something along these lines

for (int i = 1; i <= 5; i++) {
    Console.WriteLine("On the " + i + " day of christmast my true love gave to me");
    switch (i) {
    case 5:
        Console.WriteLine("5 Gold Rings");
        goto case 4;
    case 4:
        Console.WriteLine("4 Colly Birds");
        goto case 3;
    case 3:
        Console.WriteLine("3 French Hens");
        goto case 2;
    case 2:
        Console.WriteLine("2 Turtle Doves");
        goto case 1;
    case 1:
        Console.WriteLine("And a Partridge in a Pear Tree");
        break;
    }
    Console.WriteLine("-");
}

10 years later I tend to agree with him. At the time we were doing java which does fall through, had to fake it for C#.

like image 35
Chris Sainty Avatar answered Oct 06 '22 23:10

Chris Sainty