The CSharp Switch Statement – How To Go From Zero To Hero

The CSharp switch statement is a powerful tool for streamlining your code and making it easier to read and maintain. Switch statements are used to evaluate an expression and then execute code based on the value of that expression. By using switch statements, you can simplify even complex logic into straightforward code.

The CSharp switch statement is generally more efficient than traditional if-else statements, allowing your code to execute faster and with less overhead. Switch statements also make your code more readable, helping you and your colleagues to understand the logic and purpose of your code.

It is important to understand CSharp switch statements in order to use them effectively. This article will cover everything you need to know to master CSharp switch statements, including the basics of how they work, tips for using advanced techniques, and a discussion of the benefits and drawbacks to using them in your code.


Basics of CSharp Switch Statements

CSharp switch statements are used to evaluate a variable’s value and select the appropriate code block based on that value. Switch statements are especially useful when you need to test one variable against multiple values, instead of using a series of if-else statements.

The syntax of a CSharp switch statement is as follows:

switch (variable) {
    case value1:
        // code block for value1
        break;
    case value2:
        // code block for value2
        break;
    default:
        // code block for any other value
        break;
}

One of the benefits of CSharp switch statements is that they can make code easier to read and understand when you have multiple conditions that need to be checked. Compared to using nested if-else statements, switch statements result in more concise and organized code.

As an example, consider a scenario where you have a variable dayOfWeek that can take on the values Monday through Friday. Instead of using multiple if-else statements, you can use a switch statement:

switch (dayOfWeek) {
    case "Monday":
        Console.WriteLine("Today is Monday.");
        break;
    case "Tuesday":
        Console.WriteLine("Today is Tuesday.");
        break;
    case "Wednesday":
        Console.WriteLine("Today is Wednesday.");
        break;
    case "Thursday":
        Console.WriteLine("Today is Thursday.");
        break;
    case "Friday":
        Console.WriteLine("Today is Friday.");
        break;
    default:
        Console.WriteLine("Invalid day of the week.");
        break;
}

Switch Statement Variables

The variable used within a switch statement is the value that you want to check multiple conditions against. It can be of any data type, including numeric types, strings, and enumerations.

It’s important to understand how variables work within a switch statement, as they are the key component that determines which code block is executed. If the value of the variable matches one of the case values, the code block for that case will execute. If the value of the variable doesn’t match any of the defined case values, the code block in the default case will execute.

For example, the following code uses a string variable called fruit:

string fruit = "orange";
switch (fruit) {
    case "apple":
        Console.WriteLine("Fruit is an apple.");
        break;
    case "banana":
        Console.WriteLine("Fruit is a banana.");
        break;
    case "orange":
        Console.WriteLine("Fruit is an orange.");
        break;
    default:
        Console.WriteLine("Unknown fruit.");
        break;
}

In this case, the string “orange” matches the case value “orange”, so the code block associated with that case will execute and “Fruit is an orange.” will be printed to the console.

Handling Multiple Cases

A switch statement can handle multiple cases by placing multiple case values after the case keyword and separating them with commas. The syntax is as follows:

switch (variable) {
    case value1:
    case value2:
        // code block for value1 or value2
        break;
    case value3:
        // code block for value3
        break;
    default:
        // code block for any other value
        break;
}

For example, consider a scenario where you have a variable direction that can take on the values North, South, East, and West. You can handle both North and South with the same code block by using multiple case values:

switch (direction) {
    case "North":
    case "South":
        Console.WriteLine("You're heading in a northerly/southerly direction.");
        break;
    case "East":
        Console.WriteLine("You're heading in an easterly direction.");
        break;
    case "West":
        Console.WriteLine("You're heading in a westerly direction.");
        break;
    default:
        Console.WriteLine("Invalid direction.");
        break;
}

In this case, if the value of direction is either “North” or “South”, the code block for those cases will execute, resulting in “You’re heading in a northerly/southerly direction.” being printed to the console. Watch this video for more CSharp switch statement examples:

YouTube player

Advanced Techniques with C# Switch Statements

Fall-throughs

As you begin to master the basics of C# switch statements, it’s important to explore some of the more advanced techniques. One example would be fall-through control, which is the ability to specify which cases should be executed if the condition in a switch statement is met. Fall-through can be a helpful technique to streamline your code. By controlling which cases are executed, you can avoid repeating the same code over and over in each case. Instead, you can just include one case with the shared code and execute that case whenever appropriate.

Patterns

Another technique is the use of patterns in a switch statement. Patterns can be used to help match the input of your switch statement with a specific case. This feature was introduced in C# 7.0 and can be useful in simplifying your code. To use patterns in a switch statement, you must first understand the various pattern constructs available: constant, type, var, and underscore. Next, you’ll need to use these constructs to write patterns that will match your input with a specific case.

Here is an example of how to use patterns in a C# switch statement:

public int GetNumber(object obj)
{
    switch (obj)
    {
        case int i:
            return i;
        case string s when int.TryParse(s, out int i):
            return i;
        default:
            return 0;
    }
}

In this example, the switch statement takes in an object and returns an integer. The first case matches if the input is an integer. The second case matches if the input is a string that can be parsed into an integer. The “when” keyword is used to specify additional conditions for the case. Finally, the default case is executed if no other cases are matched.

Using Enumerations in C# Switch Statements

Enumerations can be extremely useful in a switch statement. By using an enumeration, you’re able to create a type-safe way of specifying a limited set of values for a variable. When you use an enumeration in a switch statement, you’re able to handle all the possible values for that enumeration in a concise and readable manner.

Here is an example of how to use an enumeration in a switch statement:

public enum Status
{
    Unknown,
    Active,
    Inactive
}

public void SetStatus(Status status)
{
    switch (status)
    {
        case Status.Unknown:
            Console.WriteLine("Unknown status");
            break;
        case Status.Active:
            Console.WriteLine("Active status");
            break;
        case Status.Inactive:
            Console.WriteLine("Inactive status");
            break;
        default:
            throw new ArgumentException("Invalid status.");
    }
}

In this example, the switch statement takes in a Status enumeration and writes the corresponding message to the console. By using enumerations, you’re able to handle all the possible states in a clean and concise manner, making your code easier to read and maintain.


Benefits and Drawbacks of Using C# Switch Statements

The Pros of C# Switch Statements

Switch statements offer a number of benefits that make them valuable tools when programming with C#. One such benefit is that they provide an intuitive and concise way to handle multiple conditions in your code. This means that you won’t have to write a large number of if-else statements, which can become hard to read and maintain over time.

Switch statements also make it easier to update or adjust your code, since adding or removing a case only requires modifying the existing code. Additionally, switch statements can make your code run faster and use fewer resources since they provide a shortcut for the program to identify the correct branch of code to execute.

The Cons of C# Switch Statements

While there are many benefits to using switch statements, there are also some drawbacks to consider. For example, they can become complicated or difficult to read if there are too many cases being handled within a single switch statement. Overuse of switch statements can also result in code that is harder to maintain and more prone to errors.

When deciding whether or not to use switch statements in your code, it is important to evaluate the specific circumstances in which they will be utilized. It may be helpful to consider how easy it will be to read and modify the code in the future, and whether there are simpler or more efficient ways to achieve the same result. Below is an example code snippet that showcases both the benefits and drawbacks of using switch statements.

// Example code showcasing the use of a C# switch statement
switch(menuInput)
{
    // Case 1 represents the "File" option in the menu
    case 1:
        Console.WriteLine("File option selected.");
        break;
    // Case 2 represents the "Edit" option in the menu
    case 2:
        Console.WriteLine("Edit option selected.");
        break;
    // Case 3 represents the "View" option in the menu
    case 3:
        Console.WriteLine("View option selected.");
        break;
    // Case 4 represents the "Help" option in the menu
    case 4:
        Console.WriteLine("Help option selected.");
        break;
    // Default case is triggered if none of the other cases match the input value
    default:
        Console.WriteLine("Invalid selection. Please try again.");
        break;
}

As you can see, this example code demonstrates how a switch statement can streamline your code by providing an efficient way to handle multiple menu selections. However, if there were many more menu options that the switch statement had to handle, it could become difficult to read and maintain over time.


Wrapping Up CSharp switch statement

In this article, we’ve learned about the basics of C# switch statements and how they can simplify our code and streamline our projects. We’ve gone over together various topics such as switch statement variables, handling multiple cases, and advanced techniques like fall-through and pattern matching. I’ve also shared the benefits and drawbacks of using C# switch statements, and the importance of being critical when deciding to use them.

To incorporate C# switch statements into your code, it’s important to start by practicing with simple examples and then move on to more complex scenarios. Be mindful of the potential drawbacks, but don’t be afraid to use switch statements when appropriate.

Thank you for reading and I hope you found this article helpful. Don’t forget to subscribe to my free weekly newsletter and check out my YouTube channel!

Affiliations:

These are products & services that I trust, use, and love. I get a kickback if you decide to use my links. There’s no pressure, but I only promote things that I like to use!

      • RackNerd: Cheap VPS hosting options that I love for low-resource usage!
      • Contabo: Alternative VPS hosting options with very affordable prices!
      • ConvertKit: This is the platform that I use for my newsletter!
      • SparkLoop: This service helps me add different value to my newsletter!
      • Opus Clip: This is what I use for help creating my short-form videos!
      • Newegg: For all sorts of computer components!
      • Bulk Supplements: For an enormous selection of health supplements!
      • Quora: I try to answer questions on Quora when folks request them of me!

    author avatar
    Nick Cosentino Principal Software Engineering Manager
    Principal Software Engineering Manager at Microsoft. Views are my own.

    Leave a Reply