How to Use Switch in C#?

In computer programming languages, a switch statement is used to control the flow of the program depending on the value of a variable or expression. The switch statement works quite similarly to the if the condition, however, there are some logical differences.

This article will teach you about the Switch statement in C#. We will go through some examples to better understand the concept.

What is Switch in C#?

A switch statement in C# executes one of many code blocks depending on some condition. C# also provides if-else statements to achieve the conditional execution of code blocks, however, the switch statement makes the code more readable and efficient especially when we have a large number of cases.

Syntax of Switch in C#

‎
switch (expression/variable)
{
    case value_1:
        // if expression(or variable) = value_1 this block executes
        break;
    case value_2:
        // if expression(or variable) = value_1 this block executes
        break;
    . 
    .
    .
    default:
        // if no case matches, this block execute 
}
‎

In the above syntax: 

  • We have an expression/variable that returns a value.
  • Cases that define the conditions to be compared with the expression/value.
  • The break statement stops the execution of the switch block.
  • A default statement at the end, that executes if no cases match the expression.

Why do we use Switch in C#?

We use Switch in C# to execute a piece of code only when a certain condition is satisfied. There are plenty of real-life examples around us that implement the switch statement. Let’s take such an example that will arise your interest before moving to the code example of the Switch in C#.

Example: When we are at a restaurant order screen, we are given a list of food categories to select from. For instance, the list contains Fast Food, Seafood, and Drinks. When we select one of the categories, it displays the items present in that category.

Now, we can consider the Switch statement, which implements the cases for each category and displays the items according to the expression containing the selected category.

The interesting part is the default statement in this example and that can be when the user selects exit without selecting any category.

How to use Switch in C#?

In this section, we will learn Switch in C# with some practical code examples. You must practice these examples to get a grip on this topic.

We use Switch Statement in C# using the keyword switch() that accepts any valid expression or variable. Case: keyword is used to specify the condition and finally the default: statement is used to execute if no condition satisfies the cases.

Example 1. In this example, we use Switch to check if the alphabet is a vowel or a consonant.

‎
using System;

namespace Conditional
{
    class SwitchExample
    {
        public static void Main(string[] args)
        {
            char x;
            Console.WriteLine("Type a character");
            x = Convert.ToChar(Console.ReadLine());
 
            switch(Char.ToLower(x))
            {
                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("consonant");
                    break;
            }
        }
    }
}
‎

Example 2. In this example, we use the Switch statement with grouped cases and check if the typed string is a working day or a weekend.

‎
using System;
 
namespace Conditional
{
    class SwitchCase
    {
        public static void Main(string[] args)
        {
            char ch;
            Console.WriteLine("Enter a day name");
            ch = Convert.ToChar(Console.ReadLine());
 
            switch(Char.ToLower(ch))
            {
                case 'Monday':
                case 'Tuesday':
                case 'Wednesday':
                case 'Thursday':
                case 'Friday':
                    Console.WriteLine("Working Day");
                    break;
                default:
                    Console.WriteLine("Weekend");
                    break;
            }
        }
    }
}
‎

Conclusion

In this article, we have learned the switch in C#. The witch statement works with limited data types. In C#, these data types are;

  • Bool, char, and integral type
  • Enum
  • String
  • Nullable types of the above data types

A good rule of thumb is to always prefer Switch Statements if the code requires more than two if-else statements.


Subscribe Now!

Subscribe Us For Latest Articles