Search This Blog

Tuesday, October 22, 2013

Switch statement C#

C# > Statements > switch

Switch selects a switch section to execute from a list of values

Switch expression: numeric, char, enum or string.
Every statement sequence in a case must be terminated with:
  • break 
  • return
  • goto
  • throw
If no case label matches default.
If no default specified continuation after the switch statement.

Example:

  private void TestSwitch(int a)
        {
            int b = 0;
            switch (a)
            {
                case 1:
                    b += 1;
                    break;
                case 2:
                    b += 1;
                    goto case 1;
                case 3:
                    return;
                default:
                   MessageBox.Show("Invalid selection.");
                   break;
            }
        }