0
0
C Sharp (C#)programming~5 mins

Switch statement execution in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A switch statement helps you choose what to do based on different values. It makes your code cleaner and easier to read when you have many options.

You want to perform different actions depending on a variable's value.
You have many conditions to check against one variable.
You want to avoid writing many if-else statements.
You want your code to be easier to understand and maintain.
Syntax
C Sharp (C#)
switch (variable)
{
    case value1:
        // code to run if variable == value1
        break;
    case value2:
        // code to run if variable == value2
        break;
    default:
        // code to run if variable does not match any case
        break;
}

Each case checks if the variable matches a value.

The break stops the switch from running other cases.

Examples
This example prints the name of the day based on the number.
C Sharp (C#)
int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    default:
        Console.WriteLine("Unknown day");
        break;
}
This example shows how multiple cases can share the same code.
C Sharp (C#)
char grade = 'B';
switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent");
        break;
    case 'B':
    case 'C':
        Console.WriteLine("Well done");
        break;
    case 'D':
        Console.WriteLine("You passed");
        break;
    default:
        Console.WriteLine("Try again");
        break;
}
Sample Program

This program checks the value of number and prints a message for 1, 2, or 3. If the number is not 1, 2, or 3, it prints "Number is unknown".

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int number = 2;
        switch (number)
        {
            case 1:
                Console.WriteLine("Number is one");
                break;
            case 2:
                Console.WriteLine("Number is two");
                break;
            case 3:
                Console.WriteLine("Number is three");
                break;
            default:
                Console.WriteLine("Number is unknown");
                break;
        }
    }
}
OutputSuccess
Important Notes

Always include a default case to handle unexpected values.

Forgetting break can cause the program to run multiple cases unintentionally.

Summary

Switch statements help choose actions based on a variable's value.

Use case for each value and break to stop.

Include a default case for any other values.