Language: EN

csharp-condicional-switch

What is and how to use the conditional SWITCH in C#

The switch conditional is a control structure in C# that provides a way to execute different blocks of code based on the value of an expression.

The switch conditional allows evaluating the value of an expression and executing specific code blocks based on different possible values of that expression.

It is sometimes used as a cleaner and more readable alternative to a series of nested if-else statements. Although, many people (myself included) believe that instead of improving readability, it usually worsens it.

Basic Syntax

The basic syntax of a switch conditional in C# is as follows:

switch (expression)
{
    case value1:
        // Code to execute if expression equals value1
        break;
    case value2:
        // Code to execute if expression equals value2
        break;
    ...
    default:
        // Code to execute if expression does not match any case
        break;
}
  • expression: It is the expression whose value is evaluated in each case
  • case: Represents a specific value that is compared with the expression
  • default: Optionally, a default block can be included

The default block will execute if none of the previous cases match the value of the expression (it is optional, but it is normal to have one).

Let’s see it with a simple example where a switch conditional is used to print a number on the screen.

int number = 2;

switch (number)
{
    case 1:
        Console.WriteLine("One");
        break;
    case 2:
        Console.WriteLine("Two");
        break;
    case 3:
        Console.WriteLine("Three");
        break;
    default:
        Console.WriteLine("Invalid number");
        break;
}

In this case, depending on the value of number

  • 1, 2, and 3 will print the corresponding number on the screen.
  • Any other number will display “Invalid number”.

Fall-Through Between Cases

Fall-Through is the ability to “fall” from one case to another and execute multiple statements of code. Unlike other languages (like C++), “fall-through” in C# is intentionally limited.

In C# all blocks must

  • Either be empty
  • Or have a break statement

That is, it is not possible to do this by omitting the break in one case,

case 1:
    Console.WriteLine("One");
    // I cannot omit `break`
case 2:
    Console.WriteLine("Two");
// more cases

It would be possible if the case statements are completely empty. Like this:

switch (number)
{
    case 1:
    case 2:
    case 3:      
        Console.WriteLine("Less than 3");
        break;
    default:
        Console.WriteLine("Greater than 3");
        break;
}

Although, it is probably a bad idea to do this 😉.

Practical Examples

:::::::

These examples are intended to show how to use the Switch conditional. It does not mean that it is the best way to solve the problem they address. Normally, there are better alternatives.