1

I was surprised to discover that locals in switch statements are scoped to the switch statement and not to the case. Why is that? And is it good practice to add curly braces around each case as a workaround.

This won't compile:

switch (n)
{
    case 1:
       var i = 1;
       Console.WriteLine(i);
       break;
    default:
       var i = 2;
       Console.WriteLine(i);
       break;
}

This does compile:

switch (n)
{
    case 1:
    {
       var i = 1;
       Console.WriteLine(i);
       break;
    }
    default:
    {
       var i = 2;
       Console.WriteLine(i);
       break;
    }
}
Anthony Faull
  • 17,549
  • 5
  • 55
  • 73
  • 4
    Why is that? Because that's the way the language was designed. – DavidG Sep 27 '19 at 11:53
  • 2
    scope is a code between `{...}` e.g. `if (1 == 1) var i = 15; else var i = 20;` will produce the same problem. In *time of old* (`C`, early `C++`) `case`s was just a *computable* `label` (`switch` computed value and made a `goto` to label found) – Dmitry Bychenko Sep 27 '19 at 11:56
  • A duplicate with a better answer: https://stackoverflow.com/q/1074589 – H H Sep 27 '19 at 12:01
  • @Henk Added that to the dupes list. – DavidG Sep 27 '19 at 12:02
  • 2
    `And is it good practice to add curly braces around each case as a workaround` Well, this is of course only my opinion, but I think that it is perfectly acceptable to do so. – Matthew Watson Sep 27 '19 at 12:09

1 Answers1

0

This is a design choice specifically made by C#.

A variable only exists inside the innermost braces in which the variable is first declared. This makes it easy to check the variables scope just by looking, and I might guess it also makes parsing easier

Abishek Aditya
  • 802
  • 4
  • 11