C# - switch
C# includes another decision-making statement called switch. The switch statement executes the code block depending upon the resulted value of an expression.
Syntax:
switch(expression) { case <value1> // code block break; case <value2> // code block break; case <valueN> // code block break; default // code block break; }
As per the syntax above, switch statement contains an expression into brackets. It also includes multiple case labels, where each case represents a particular literal value. The switch cases are seperated by a break keyword which stops the execution of a particular case. Also, the switch can include a default case to execute if no case value satisfies the expression.
Consider the following example of a simple switch statement.
Example: switch
int x = 10; switch (x) { case 5: Console.WriteLine("Value of x is 5"); break; case 10: Console.WriteLine("Value of x is 10"); break; case 15: Console.WriteLine("Value of x is 15"); break; default: Console.WriteLine("Unknown value"); break; }
The switch statement can include expression or variable of any data type such as string, bool, int, enum, char etc.
Example: switch statement
string statementType = "switch"; switch (statementType) { case "if.else": Console.WriteLine("if...else statement"); break; case "ternary": Console.WriteLine("Ternary operator"); break; case "switch": Console.WriteLine("switch statement"); break; }
Goto in switch:
The switch case can use goto to jump over a different case.
Example: goto in switch case
string statementType = "switch"; switch (statementType) { case "DecisionMaking": Console.Write(" is a decision making statement."); break; case "if.else": Console.Write("if-else"); break; case "ternary": Console.Write("Ternary operator"); break; case "switch": Console.Write("switch statement"); goto case "DecisionMaking"; }
0 Comments