Switch statements in C# provide a way to execute different parts of code based on the value of a variable. They are a more readable alternative to multiple if-else statements when you need to compare a variable against several possible values.

Key Concepts

  1. Syntax: The basic structure of a switch statement.
  2. Case Labels: Define the possible values the variable can take.
  3. Break Statement: Prevents fall-through to subsequent cases.
  4. Default Case: Executes if none of the case labels match the variable's value.
  5. Pattern Matching: Advanced feature for more complex conditions.

Basic Syntax

switch (variable)
{
    case value1:
        // Code to execute if variable == value1
        break;
    case value2:
        // Code to execute if variable == value2
        break;
    // More cases...
    default:
        // Code to execute if none of the above cases match
        break;
}

Example

Let's look at a practical example to understand how switch statements work.

using System;

class Program
{
    static void Main()
    {
        int dayOfWeek = 3;

        switch (dayOfWeek)
        {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
            case 4:
                Console.WriteLine("Thursday");
                break;
            case 5:
                Console.WriteLine("Friday");
                break;
            case 6:
                Console.WriteLine("Saturday");
                break;
            case 7:
                Console.WriteLine("Sunday");
                break;
            default:
                Console.WriteLine("Invalid day");
                break;
        }
    }
}

Explanation

  • Variable: dayOfWeek is the variable being evaluated.
  • Case Labels: Each case represents a possible value of dayOfWeek.
  • Break Statement: Ensures that once a matching case is found, the switch statement exits.
  • Default Case: Handles any values not explicitly covered by the case labels.

Practical Exercises

Exercise 1: Basic Switch Statement

Write a program that takes an integer input from the user and prints the corresponding month name. If the input is not between 1 and 12, print "Invalid month".

Solution

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a month number (1-12): ");
        int month = int.Parse(Console.ReadLine());

        switch (month)
        {
            case 1:
                Console.WriteLine("January");
                break;
            case 2:
                Console.WriteLine("February");
                break;
            case 3:
                Console.WriteLine("March");
                break;
            case 4:
                Console.WriteLine("April");
                break;
            case 5:
                Console.WriteLine("May");
                break;
            case 6:
                Console.WriteLine("June");
                break;
            case 7:
                Console.WriteLine("July");
                break;
            case 8:
                Console.WriteLine("August");
                break;
            case 9:
                Console.WriteLine("September");
                break;
            case 10:
                Console.WriteLine("October");
                break;
            case 11:
                Console.WriteLine("November");
                break;
            case 12:
                Console.WriteLine("December");
                break;
            default:
                Console.WriteLine("Invalid month");
                break;
        }
    }
}

Exercise 2: Switch with Pattern Matching

Write a program that takes a string input representing a shape ("circle", "square", "triangle") and prints the number of sides. Use pattern matching in the switch statement.

Solution

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a shape (circle, square, triangle): ");
        string shape = Console.ReadLine().ToLower();

        switch (shape)
        {
            case "circle":
                Console.WriteLine("A circle has 0 sides.");
                break;
            case "square":
                Console.WriteLine("A square has 4 sides.");
                break;
            case "triangle":
                Console.WriteLine("A triangle has 3 sides.");
                break;
            default:
                Console.WriteLine("Unknown shape");
                break;
        }
    }
}

Common Mistakes and Tips

  • Forgetting the break statement: This can cause unintended fall-through behavior.
  • Not handling all possible values: Always include a default case to handle unexpected values.
  • Case Sensitivity: Remember that string comparisons in switch statements are case-sensitive unless explicitly handled.

Conclusion

Switch statements are a powerful tool for controlling the flow of your program based on the value of a variable. They make your code more readable and maintainable compared to multiple if-else statements. Practice using switch statements with different data types and scenarios to become proficient in their use.

© Copyright 2024. All rights reserved