#173 – The switch Statement
December 7, 2010 2 Comments
Use the switch statement in C# to execute one of several different blocks of code based on the possible values of a single expression.
// 1 = Easy, 2 = Normal, 3 = Hard uint gameDifficulty = GetDifficulty(); uint score = GetScore(); uint totalScore; switch (gameDifficulty) { case 1: Console.WriteLine("This is an EASY game"); totalScore = score / 2; break; case 2: Console.WriteLine("This is a NORMAL game"); totalScore = score; break; case 3: Console.WriteLine("This is a HARD game"); totalScore = score * 2; break; }
The type of the expression must be one of the built-in primitive value types, a string or an enum.
The expression is evaluated and if the resulting value is listed as a value in one of the case clauses, the statements within that case are executed.
Each case clause must be terminated with some sort of jump statement. The break statement is typically used, which causes control to jump to the next statement following the switch statement.