Wednesday, October 31, 2007

Switch Case C#

For some reason I find myself having to look this up every time I go to use it.

Switch is like Select in VB. The structure of it is as follows.

switch (variable)
case value1:
case value2:
case value3:
  • Switch is followed by a variable in parenthesis. This the variable that you are checking the value of.
  • Each value that you want to check the variable against is in a case vale block.
    • Must have a colon after the value.
    • Each statement int he block must be terminated with a semicolon.
    • Each block must have a break at the end of it. C# does not allow falling through to one case to the other, but you can do several empty cases in a row that all fall through to one code block. The break tells it not to do this. For example:
      case 1:
      case 2:
      case 3:
      In this example if the variable is 1, 2, or 3 it runs do something.
  • There can be a default case that executes if the variable does not match any of the cases.
  • It appears as though one can include a goto statement in their case block also. For example "goto case 17" jumps you to case one. You could execute code in case 45 and then jump to case 17 and run its code as well, even though the variable is not equal to 17.
  • All of the case blocks are surrounded by {}. The opening { is after switch (variable). The closing } is after the last case block of code.

No comments: