image

C# Case Statement : Switching Between Multiple Cases

In C# programming, the switch statement is a control flow statement that allows you to execute different blocks of code based on different conditions. It's commonly used when you have multiple conditions to evaluate, and you want to execute different code paths based on those conditions. The switch statement is often used as an alternative to multiple if...else statements, providing a more readable and efficient way to handle complex conditionals.

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

switch (expression)

{

    case value1:

        // code block

        break;

    case value2:

        // code block

        break;

    ...

    default:

        // code block

        break;

}

Here's how it works:

  1. The expression is evaluated, and its resulting value is used to determine which case block to execute.
  2. If the expression's value matches a case value, the corresponding code block is executed.
  3. The break statement is used to exit the switch statement once a matching case is found and its code block is executed.
  4. If no case value matches the expression's value, and a default case is present, the code block under the default case is executed.
  5. If no case value matches the expression's value, and there is no default case, the switch statement is exited without executing any code block.

Now, let's dive deeper into handling multiple cases in a switch statement.

Handling Multiple Cases with the Same Code Block

In some situations, you may want to execute the same code block for multiple case values. In C#, you can group multiple cases together by listing them one after another, separated by commas. Here's an example:

int day = 4;

string dayName;

switch (day)

{

    case 1:

    case 2:

    case 3:

    case 4:

    case 5:

        dayName = "Weekday";

        break;

    case 6:

    case 7:

        dayName = "Weekend";

        break;

    default:

        dayName = "Invalid day";

        break;

}

Console.WriteLine(dayName); // Output: Weekday

In this example, the cases 1, 2, 3, 4, and 5 are grouped together, and the same code block will be executed for any of those values.

Fallthrough in Switch Statements

By default, when a matching case is found, and its code block is executed, the switch statement exits immediately after encountering the break statement. However, if you omit the break statement, the execution will "fall through" to the next case block, regardless of whether its condition matches or not.

Here's an example that demonstrates fallthrough behavior:

int score = 85;

string grade;

switch (score / 10)

{

    case 10:

        grade = "A+";

        break;

    case 9:

        grade = "A";

        goto case 8;

    case 8:

        grade = "B";

        break;

    case 7:

        grade = "C";

        break;

    case 6:

        grade = "D";

        break;

    default:

        grade = "F";

        break;

}

Console.WriteLine(grade); // Output: B

In this example, when score / 10 evaluates to 8, the code block for case 9 is executed, and then it falls through to the case 8 block, where the grade is set to "B". The goto case 8; statement is used to explicitly jump to the case 8 block, even though the condition for case 9 was met.

It's generally recommended to use the break statement to explicitly exit the switch statement after a matching case block is executed. Fallthrough behavior can make code harder to read and maintain, and it can also lead to unintended consequences if not used carefully.

Patterns in Switch Statements

In addition to using constant values in case statements, C# also allows you to use patterns, which can be more powerful and flexible than simple constant values. Patterns can match various types of expressions, including ranges, types, and more.

Here's an example that demonstrates the use of patterns in a switch statement:

object value = 42;

switch (value)

{

    case int i:

        Console.WriteLine($"The value is an integer: {i}");

        break;

    case string s:

        Console.WriteLine($"The value is a string: {s}");

        break;

    case null:

        Console.WriteLine("The value is null");

        break;

    default:

        Console.WriteLine("The value is something else");

        break;

}

In this example, the switch statement checks the type of the value object and executes the corresponding code block based on the type. The case int i: pattern matches if value is an integer, and the variable i is assigned the integer value. Similarly, the case string s: pattern matches if value is a string, and the variable s is assigned the string value. The case null: pattern matches if value is null.

Patterns can be combined with other patterns using the and and or operators, allowing you to create more complex matching conditions.

Switch Expression

In addition to the traditional switch statement, C# 8.0 introduced the switch expression, which provides a more concise syntax and supports pattern matching. The switch expression is similar to a switch statement, but it returns a value based on the matched case.

Here's an example of using a switch expression:

object value = 42;

string result = value switch

{

    int i => $"The value is an integer: {i}",

    string s => $"The value is a string: {s}",

    null => "The value is null",

    _ => "The value is something else"

};

Console.WriteLine(result); // Output: The value is an integer: 42

In this example, the switch expression evaluates the value object and returns a string based on the matched case. The => syntax is used to specify the expression to be evaluated and returned for each case.

FAQs

Can I use continue instead of break in a switch statement?

No, the continue statement is not allowed inside a switch statement in C#. The break statement is used to exit the switch statement after a matching case block is executed. If you want to skip the execution of the current case block and move to the next iteration, you can use a loop construct (like for or while) around the switch statement and use the continue statement within the loop.

Can I nest switch statements inside other switch statements?

Yes, you can nest switch statements inside other switch statements in C#. This can be useful when you need to handle complex conditional logic based on multiple expressions.

How does the switch statement handle null values?

If the expression in a switch statement evaluates to null, and there is a case null: block, that block will be executed. If there is no case null: block, and the expression evaluates to null, the default block (if present) will be executed.

Can I use patterns with the traditional switch statement?

Yes, you can use patterns with the traditional switch statement in C# 7.0 and later versions. However, the syntax is slightly different from the switch expression. You need to use the case keyword followed by the pattern, and then use the when keyword to specify additional conditions.

What is the performance difference between switch statements and if...else statements?

Generally, switch statements are more efficient than long chains of if...else statements, especially when dealing with a large number of conditions. This is because the compiler can generate more optimized code for switch statements, using techniques like jump tables or binary search trees. However, for a small number of conditions, the performance difference may be negligible.

Share On