C# Switch

Concept of switch statement in C#.

* Switch case is often more efficient than 'if-else' chains when handling multiple conditions, as it directly jumps to the matching case instead of evaluating each condition sequentially.

Switch Case

The 'switch' statement is a control flow statement that allows you to select one of many code blocks to be executed based on the value of an expression. Here's the basic syntax of a 'switch' statement:

switch (expression)
{
    case value1:
        // Code to be executed if expression matches value1
        break;

    case value2:
        // Code to be executed if expression matches value2
        break;

    // Additional cases as needed

    default:
        // Code to be executed if none of the cases match
        break;
}

Here's a simple example:

cs Copy Code
using System;

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

        switch (number)
        {
            case 1:
                Console.WriteLine("You entered one.");
                break;

            case 2:
                Console.WriteLine("You entered two.");
                break;

            case 3:
                Console.WriteLine("You entered three.");
                break;

            default:
                Console.WriteLine("Invalid input.");
                break;
        }
    }
}

Remember: use the 'break' statement after each 'case' block to exit the 'switch' statement.

Output:
Enter a number (1-3): 2
You entered two.

In this example, the user is prompted to enter a number, and the program uses a 'switch' statement to determine which message to display based on the entered number. The 'default' case is executed if none of the specified cases match the value of the expression ('number' in this case).

What is New?

We have just updated this website & still working on adding new content & updating existing features.