In this tutorial, we will learn about switch statement in C# and how to use them with examples.

A switch statement allows a variable to be tested for equality against a rundown of values. Each value is known as a case, and the variable being switched on is checked for each switch case.

Switch statement can be used to replace the if…else if statement in C#. The benefit of using switch over if…else if statement is the codes will look a lot of cleaner and readable with switch.

The syntax of switch statements is:

switch (variable/expression)
{
    case value1:
        // Statements executed if expression(or variable) = value1
        break;
    case value2:
        // Statements executed if expression(or variable) = value1
        break;
    ... ... ... 
    ... ... ... 
    default:
        // Statements executed if no case matches
}

The switch statements assesses the expression (or variable) and compare its value with the values (or expression) of each case (value1, value2, … ). At the point when it finds the coordinating with value, the statements inside that case are executed.

Yet, on the off chance that none from what was just mentioned cases coordinates with the expression, the statements inside default block is executed. The default statement toward the finish of switch is like the else block in if else statement.

Anyway an issue with the switch statement is, the point at which the coordinating with value is discovered, it executes all statements after it until the finish of switch block.

To keep away from this, we use break statement toward the finish of each case. The break statement prevents the program from executing non-coordinating with statements by ending the execution of switch statement.

To learn more about break statement, visit C# break statement.



Example 1: C# switch Statement

using System;
 
namespace Conditional
{
    class SwitchCase
    {
        public static void Main(string[] args)
        {
            char ch;
            Console.WriteLine("Enter an alphabet");
            ch = Convert.ToChar(Console.ReadLine());
 
            switch(Char.ToLower(ch))
            {
                case 'a':
                    Console.WriteLine("Vowel");
                    break;
                case 'e':
                    Console.WriteLine("Vowel");
                    break;
                case 'i':
                    Console.WriteLine("Vowel");
                    break;
                case 'o':
                    Console.WriteLine("Vowel");
                    break;
                case 'u':
                    Console.WriteLine("Vowel");
                    break;
                default:
                    Console.WriteLine("Not a vowel");
                    break;
            }
        }
    }
}

At the point when we run the program, the output will be:

Enter an alphabet
X
Not a vowel

In this example, the user is prompted to enter an alphabet. The alphabet is converted to lowercase by using ToLower() strategy on the off chance that it is in uppercase.

At that point, the switch statement checks whether the alphabet entered by user is any of a, e, I, o or u.

In the event that one of the case matches, Vowel is printed in any case the control goes to default block and Not a vowel is printed as output.

Since, the output for all vowels are something similar, we can join the cases as:


Example 2: C# switch Statement with grouped cases

using System;
 
namespace Conditional
{
    class SwitchCase
    {
        public static void Main(string[] args)
        {
            char ch;
            Console.WriteLine("Enter an alphabet");
            ch = Convert.ToChar(Console.ReadLine());
 
            switch(Char.ToLower(ch))
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    Console.WriteLine("Vowel");
                    break;
                default:
                    Console.WriteLine("Not a vowel");
                    break;
            }
        }
    }
}

The output of the two programs is same. In the above program, all vowels print the output Vowel and breaks from the switch statement.

Although switch statement makes the code look cleaner than if…else if statement, switch is confined to work with limited data types. Switch statement in C# just works with:

• Primitive data types: bool, char and fundamental sort

• Enumerated Types (Enum)

• String Class

• Nullable sorts of above data types


Example 3: Simple calculator program using C# switch Statement

using System;
 
namespace Conditional
{
    class SwitchCase
    {
        public static void Main(string[] args)
        {
            char op;
            double first, second, result;
             
            Console.Write("Enter first number: ");
            first = Convert.ToDouble(Console.ReadLine());
            Console.Write("Enter second number: ");
            second = Convert.ToDouble(Console.ReadLine());
            Console.Write("Enter operator (+, -, *, /): ");
            op = (char)Console.Read();
 
            switch(op)
            {
                case '+':
                    result = first + second;
                    Console.WriteLine("{0} + {1} = {2}", first, second, result);
                    break;
                 
                case '-':
                    result = first - second;
                    Console.WriteLine("{0} - {1} = {2}", first, second, result);
                    break;
                 
                case '*':
                    result = first * second;
                    Console.WriteLine("{0} * {1} = {2}", first, second, result);
                    break;
                 
                case '/':
                    result = first / second;
                    Console.WriteLine("{0} / {1} = {2}", first, second, result);
                    break;
 
                default:
                    Console.WriteLine("Invalid Operator");
                    break;
                     
            }
        }
    }
}

At the point when we run the program, the output will be:

Enter first number: -13.11
Enter second number: 2.41
Enter operator (+, -, *, /): *
-13.11 * 2.41 = -31.5951

The above program takes two operands and an operator as input from the user and plays out the activity based on the operator.

The input are taken from the user using the ReadLine() and Read() technique. To learn more, visit C# Basic Input and Output.

The program uses switch case statement for decision making. On the other hand, we can use if-else if ladder to play out a similar activity.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.


0 Comments

Leave a Reply