C# Switch statement with/without curly brackets.... what's the difference?

goodguys_activate picture goodguys_activate · Sep 6, 2010 · Viewed 23.4k times · Source

Has C# always permitted you to omit curly brackets inside a switch() statement between the case: statements?

What is the effect of omitting them, as javascript programmers often do?

Example:

switch(x)
{
  case OneWay:
  {                               //  <---- Omit this entire line
    int y = 123;
    FindYou(ref y);
    break;
  }                               //  <---- Omit this entire line
  case TheOther:
  {                               //  <---- Omit this entire line
    double y = 456.7; // legal!
    GetchaGetcha(ref y);
    break;
  }                               //  <---- Omit this entire line
}

Answer

Dirk Vollmar picture Dirk Vollmar · Sep 6, 2010

Curly braces are not required, but they might come in handy to introduce a new declaration space. This behavior hasn't changed since C# 1.0 as far as I know.

The effect of omitting them is that all variables declared somewhere inside the switch statement are visible from their point of declaration throughout all case branches.

See also Eric Lippert's example (case 3 in the post):

Four switch oddities

Eric's example:

switch(x)
{
  case OneWay:
    int y = 123;
    FindYou(ref y);
    break;
  case TheOther:
    double y = 456.7; // illegal!
    GetchaGetcha(ref y);
    break;
}

This does not compile because int y and double y are in the same declaration space introduced by the switch statement. You can fix the error by separating the declaration spaces using braces:

switch(x)
{
  case OneWay:
  {
    int y = 123;
    FindYou(ref y);
    break;
  }
  case TheOther:
  {
    double y = 456.7; // legal!
    GetchaGetcha(ref y);
    break;
  }
}