C# Keywords Tutorial Part 12: case

C# Keywords Tutorial Part 12: case

Numerous features are offered by the popular object-oriented programming language C# to improve the readability and structure of code. The “case” keyword, which is used in switch statements to run a certain block of code based on a given expression, is one of C#’s most beneficial features.

The switch statement compares an evaluated expression to the cases specified in the switch statement. The code block related to that case will be run if the expression matches one of the cases. Here is a straightforward switch statement illustration:

int number = 3;

switch (number)
{
    case 1:
        Console.WriteLine("The number is one.");
        break;
    case 2:
        Console.WriteLine("The number is two.");
        break;
    case 3:
        Console.WriteLine("The number is three.");
        break;
    default:
        Console.WriteLine("The number is not one, two, or three.");
        break;
}

In this example, the switch statement evaluates the value of the “number” variable and executes the appropriate code block based on the value. Since “number” is equal to 3, the code block associated with case 3 will be executed, which outputs “The number is three.” to the console.

The “default” keyword is used to specify a code block that will be executed if none of the cases match the given expression. In this example, the “default” code block will be executed if the value of “number” is not equal to 1, 2, or 3.

The “case” keyword can also be used to create ranges of values. For example, if we want to execute the same code block for values between 4 and 6, we can use the following code:

int number = 5;

switch (number)
{
    case 1:
        Console.WriteLine("The number is one.");
        break;
    case 2:
        Console.WriteLine("The number is two.");
        break;
    case 3:
        Console.WriteLine("The number is three.");
        break;
    case int n when (n >= 4 && n <= 6):
        Console.WriteLine("The number is between four and six.");
        break;
    default:
        Console.WriteLine("The number is not one, two, three, or between four and six.");
        break;
}

In this example, we use the “when” keyword along with the “case” keyword to specify a condition that must be true for the associated code block to be executed. In this case, the code block will be executed if the value of “number” is between 4 and 6, inclusive.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *