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

假装没事ソ 提交于 2019-12-03 23:25:09

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;
}

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#.

Drop through is allowed for the special case of matching multiple cases, but the comparative and range cases aren't allowed. So:

int condition = 55;
switch (condition) {
  case 1: case 3: case 4: case 5: case 10: case 12: case 14:
    // value 55 doesn't execute here anymore

  default:
    //values <1, 2, 6-9, 11, 13, >14
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!