C# Switch statement

What is a switch case statement?

The switch statement is another type of selection statement. The main purpose of the switch statement is to allow the value of a variable or an expression to control the flow of program execution. The variable or an expression is usually referred to as the control variable of the switch statement. The switch statement is divided into two main parts, switch, and case. In the switch statement, the value of a variable inside the switch block is checked with the different case expressions. If the value of the variable matches with any of the case expressions, then the statement inside that case statement executes.

The following code snippet shows an example of a switch statement:

switch (Marks) // test expression
{
case 1: //expression
{
    Console.Write("Your marks are very low");
}
break;
      case 2: //expression
      {
          Console.Write("Your marks are low");
      }
      break;
      case 3: //expression
      {
                Console.Write("Your marks are average");
      }
      break;
      case 4: //expression
      {
        Console.Write("Your marks are good");
      }
      break;
      default;
      break;
}
The keywords used in the preceding code snippet are as follows:
  • switch - Denotes a keyword from where the switch statement starts and holds a test expression within the parenthesis.
  • test expression - Represents any integral expression, such as int and char, which needs to be compared with the case expression.
  • case - Denotes a keyword that holds an expression followed by a colon(:).
  • expression - Represents any constant value, which is compared with the value of test expression.
  • break - Denotes a keyword that alters the flow of the switch statement.
  • default - Denotes a keyword that makes the code inside the default block execute in case none of the other case expressions matches with the test expression.

The switch statement contains a test expression, such as int, char, and string, and matches the cases with the value of that test expression. The program control flows from one case to another. If the case matches with the specified test expression, the program control is transferred to that specific case statement and the statements inside that case statement are executed. An optional block, known as the default case, is also present in the switch statement. It does not specify any expression and is denoted by the default keyword instead of the case keyword. If none of the case expressions matches with the test expression, the program execution is transferred to the statement following the default keyword.



Write a comment


Name Email Message