Switch Statements in C#

Switch Statements in C# with Examples

In this article, I am going to discuss the Switch Statements in C# Language with Examples. Please read our previous articles, where we discussed If Else Statements in C# Language with Examples. At the end of this article, you will understand what is Switch statement in C# and when and how to use switch statements in C# Language with Examples.

Switch Statements in C# Language:

The switch is a keyword in the C# language, and by using this keyword we can create selection statements with multiple blocks. Multiple blocks can be constructed by using the “case” keyword.

Switch case statements in C# are a substitute for long if statements that compare a variable to several integral values. The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The switch is a control statement that allows a value to change control of execution.

Switch Statements in C# Language

When do we need to go for a switch statement?

When there are several options and we have to choose only one option from the available options depending on a single condition then we need to go for a switch statement. Depending on the selected option a particular task can be performed.

Rules for Switch Statements in C# Language:
  1. The expression provided in the switch should result in a constant value otherwise it would not be valid.
  2. Duplicate case values are not allowed.
  3. The default statement is optional. Even if the switch case statement does not have a default statement, it would run without any problem.
  4. The break statement is used inside the switch to terminate a statement sequence. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  5. The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached.
  6. Nesting of switch statements is allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes the program more complex and less readable.
Syntax of Switch Statements in C# Language:

In C#, the Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type. The expression is checked for different cases and the one match is executed

Syntax of Switch Statements in C# Language

After the end of each block, it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from every case onwards after matching the case block.

Example to understand Switch Statement in C# Language:
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 2;
            switch (x)
            {
                case 1:
                    Console.WriteLine("Choice is 1");
                    break;
                case 2:
                    Console.WriteLine("Choice is 2");
                    break;
                case 3:
                    Console.WriteLine("Choice is 3");
                    break;
                default:
                    Console.WriteLine("Choice other than 1, 2 and 3");
                    break;
            }
            Console.ReadKey();
        }
    }
}

Output: Choice is 2

When we are working with nested if-else at even any point of time among those all blocks only one block gets executed. But in the switch statement, we can create more than one block depending on the requirement by removing the break statement between the blocks.

Why do we use Switch Statements instead of if-else statements in C#?

We use a switch statement instead of if-else statements because an if-else statement only works for a small number of logical evaluations of a value. If you use an if-else statement for a larger number of possible conditions then, it takes more time to write and also becomes difficult to understand.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // taking two strings value
            string topic;
            string category;

            // taking topic name
            topic = "Inheritance";

            // using compare function of string class
            if ((String.Compare(topic, "Introduction to C#") == 0) ||
                (String.Compare(topic, "Variables") == 0) ||
                (String.Compare(topic, "Data Types") == 0))
            {
                category = "Basic";
            }

            // using compare function of string class
            else if ((String.Compare(topic, "Loops") == 0) ||
                     (String.Compare(topic, "If Statements") == 0) ||
                     (String.Compare(topic, "Jump Statements") == 0))
            {
                category = "Control Flow";
            }

            // using compare function of string class
            else if ((String.Compare(topic, "Class & Object") == 0) ||
                     (String.Compare(topic, "Inheritance") == 0) ||
                     (String.Compare(topic, "Constructors") == 0))
            {
                category = "OOPS Concept";
            }

            else
            {
                category = "Not Mentioned";
            }

            System.Console.Write("Category is " + category);
            Console.ReadKey();
        }
    }
}

Output: Category is OOPS Concept

As shown in the above example, the code is not excessive but, it looks complicated to read and took more time to write. So, we use a switch statement to save time and write optimized code. Using a switch statement will provide better readability of code. Let us write the same example Using Switch Statement in C# language.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // taking two strings value
            string topic;
            string category;

            // taking topic name
            topic = "Inheritance";

            // using switch Statement
            switch (topic)
            {
                case "Introduction to C#":
                case "Variables":
                case "Data Types":

                    category = "Basic";
                    break;

                case "Loops":
                case "If Statements":
                case "Jump Statements":

                    category = "Control Flow";
                    break;

                case "Class & Object":
                case "Inheritance":
                case "Constructors":

                    category = "OOPS Concept";
                    break;

                // default case 
                default:
                    category = "Not Mentioned";
                    break;

            }

            System.Console.Write("Category is " + category);
            Console.ReadKey();
        }
    }
}

Output: Category is OOPS Concept

Using goto in the Switch Statement in C#

We can also use the goto statement in place of the break statement in the switch statement. Generally, we use a break statement to exit from the switch statement. But in some situations, the default statement is required to be executed, so in that case, we can use the goto statement. It allows the execution of default conditions in the switch statement. The goto statement is also used to jump to a labeled location in the C# program.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int greeting = 2;

            switch (greeting)
            {
                case 1:
                    Console.WriteLine("Hello");
                    goto default;
                case 2:
                    Console.WriteLine("Hi");
                    goto case 3;
                case 3:
                    Console.WriteLine("Namaste");
                    goto default;
                default:
                    Console.WriteLine("Entered value is: " + greeting);
                    break;
            }
            Console.ReadKey();
        }
    }
}
Output:

In the below program, the goto statement is used in a switch statement. Here first the case 2, i.e Hi is printed because the switch contains the value of greeting is 2, then the control transfers to the case 3 due to the presence of goto statement, so it prints Namaste and in last the control transfer to the default condition and print Entered value is: 2.

Switch Statements in C# Language with Examples

Note: You can also use continue in place of a break statement in a switch statement if your switch statement is a part of a loop, then the continue statement will cause execution to return instantly to the starting of the loop.

Example C# Switch Statement

In the below example, we will ask the user to enter an alphabet and then we will check whether that alphabet is a vowel or not using Switch Statement in C# language

using System;
namespace ControlFlowDemo
{
    class Program
    {
        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;
            }
            Console.ReadKey();
        }
    }
}
Output:

Switch Statements in C# Language with Examples

In the above example, the user is prompted to enter an alphabet. The alphabet is converted to lowercase by using the ToLower() method if it is in uppercase. Then, the switch statement checks whether the alphabet entered by the user is any of a, e, i, o, or u. If one of the cases matches, Vowel is printed otherwise the control goes to the default block and Not a vowel is printed as output. Since the output for all vowels is the same, we can join the cases as shown in the below example:

Example: C# Switch Statement with grouped cases
using System;
namespace ControlFlowDemo
{
    class Program
    {
        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;
            }
            Console.ReadKey();
        }
    }
}

The output of both programs is the same. In the above program, all vowels print the output Vowel and break from the switch statement. Although the switch statement makes the code look cleaner than the if…else if statement, the switch is restricted to work with limited data types. The switch statement in C# only works with:

  1. Primitive data types: bool, char, and integral type
  2. Enumerated Types (Enum)
  3. String Class
  4. Nullable types of the above data types

In the next article, I am going to discuss Loops in C# with Examples. Here, in this article, I try to explain Switch Statements in C# Language with Examples and I hope you like this Switch Statements in C# article. I would like to have your feedback. Please post your feedback, question, or comments about this Control Flow Statements in Java article.

Leave a Reply

Your email address will not be published.