The Switch Statement

The Switch Statement

The switch statement is another control flow statement in C# that allows you to execute different blocks of code based on the value of a single variable or expression. Here’s the basic syntax of a switch statement in C#:

switch (expression)

{

    case value1:

        // code to execute if expression == value1

        break;

    case value2:

        // code to execute if expression == value2

        break;

    // …

    default:

        // code to execute if none of the above conditions are met

        break;

}

In this syntax, expression is the variable or expression that you want to test, and value1, value2, etc. are the values that you want to test for. The default block is optional and is executed if none of the previous conditions are met.

Here’s an example of using a switch statement in C#:

int num = 2;

switch (num)

{

    case 1:

        Console.WriteLine(“one”);

        break;

    case 2:

        Console.WriteLine(“two”);

        break;

    case 3:

        Console.WriteLine(“three”);

        break;

    default:

        Console.WriteLine(“not one, two, or three”);

        break;

}

In this example, the code inside the case 2: block will execute because the value of num is 2. The break statement is used to exit the switch statement and prevent the execution of any subsequent code blocks.

You can also use the default block to handle cases where the value of the expression does not match any of the specified cases. Here’s an example:

int num = 5;

switch (num)

{

    case 1:

        Console.WriteLine(“one”);

        break;

    case 2:

        Console.WriteLine(“two”);

        break;

    case 3:

        Console.WriteLine(“three”);

        break;

    default:

        Console.WriteLine(“not one, two, or three”);

        break;

}

In this example, the code inside the default: block will execute because the value of num is not 1, 2, or 3. The switch statement is a useful tool for writing code that can make decisions based on the value of a single variable or expression. By using switch statements, you can simplify complex conditional logic and make your code easier to read and understand.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Roles/Functions of Treasury Management
Scope of Treasury Management

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?