DEV Community

Python Tutorial
Python Tutorial

Posted on

Exploring Switch Case in C#: Traditional vs. Modern Patterns

Switch Case in C

Image description

Introduction

Control flow statements are essential in programming, as they help developers execute code blocks based on conditions. In C#, one of the most commonly used control flow structures is the switch case statement. Over the years, switch case in C# has evolved from a simple, rigid structure to a more powerful and expressive feature with modern pattern matching capabilities. In this C# tutorial, we will explore the traditional switch case statement, compare it with modern pattern matching techniques, and understand when to use each approach.

Understanding the Traditional Switch Case in C

The traditional switch case statement in C# is used to compare a variable’s value against multiple cases and execute the corresponding code block. It is commonly used when there are multiple conditional branches that depend on a single expression.

Syntax of Traditional Switch Case

using System;

class Program
{
    static void Main()
    {
        int day = 3;

        switch (day)
        {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
            case 4:
                Console.WriteLine("Thursday");
                break;
            case 5:
                Console.WriteLine("Friday");
                break;
            case 6:
            case 7:
                Console.WriteLine("Weekend");
                break;
            default:
                Console.WriteLine("Invalid day");
                break;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Features of Traditional Switch Case

  • The switch statement evaluates the expression and matches it with case labels.
  • The break statement prevents fall-through to subsequent cases.
  • The default case acts as a fallback option if no match is found.
  • Multiple cases can be grouped to execute the same statement.

Limitations of Traditional Switch Case

  1. Only works with specific data types: Traditional switch supports integer, char, enum, and string but does not work well with complex objects.
  2. No support for complex conditions: It only allows exact matches and does not support logical expressions.
  3. Verbose syntax: Writing multiple cases with break statements can make the code lengthy and harder to maintain.

The Evolution: Modern Switch Case with Pattern Matching

With the introduction of C# 7.0 and later versions, Microsoft introduced pattern matching, which significantly enhanced the switch statement's capabilities. Modern switch statements can now handle more complex conditions, making them more concise and powerful.

Expression-Based Switch (C# 8.0 and Later)

The modern switch case in C# allows expression-based evaluations, making the syntax cleaner and reducing the need for break statements.

Example:

using System;

class Program
{
    static void Main()
    {
        int day = 3;
        string result = day switch
        {
            1 => "Monday",
            2 => "Tuesday",
            3 => "Wednesday",
            4 => "Thursday",
            5 => "Friday",
            6 or 7 => "Weekend",
            _ => "Invalid day"
        };

        Console.WriteLine(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Advantages of Expression-Based Switch

  1. More concise syntax: The new syntax eliminates the need for case and break keywords.
  2. No fall-through errors: The arrow syntax (=>) prevents unintended case fall-through.
  3. Supports multiple conditions per case: The or operator (6 or 7 =>) allows handling multiple cases in a single line.
  4. Supports _ as a default case: The underscore _ serves as the equivalent of the traditional default case.

Advanced Pattern Matching in Switch Case

Modern switch case in C# introduces pattern matching, which allows evaluating object properties and types within a switch statement.

Type Pattern Matching

With C# 7.0, switch statements can check for types and safely cast them.

using System;

class Program
{
    static void PrintType(object obj)
    {
        switch (obj)
        {
            case int i:
                Console.WriteLine($"Integer: {i}");
                break;
            case string s:
                Console.WriteLine($"String: {s}");
                break;
            case null:
                Console.WriteLine("Null value");
                break;
            default:
                Console.WriteLine("Unknown type");
                break;
        }
    }

    static void Main()
    {
        PrintType(10);
        PrintType("Hello");
        PrintType(null);
    }
}
Enter fullscreen mode Exit fullscreen mode

Relational and Logical Patterns (C# 9.0 and Later)

C# 9.0 introduced relational and logical patterns in switch expressions, making condition evaluation more flexible.

using System;

class Program
{
    static void Main()
    {
        int score = 85;

        string grade = score switch
        {
            >= 90 => "A",
            >= 80 and < 90 => "B",
            >= 70 and < 80 => "C",
            >= 60 and < 70 => "D",
            _ => "F"
        };

        Console.WriteLine($"Your grade: {grade}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Benefits of Modern Pattern Matching

  • Supports complex conditions using logical (and, or) and relational (>=, <=) operators.
  • Enables type safety by ensuring the variable matches a known type.
  • Improves readability by making conditions more expressive.

When to Use Traditional vs. Modern Switch Case

Use Case Traditional Switch Modern Switch (Pattern Matching)
Simple value comparisons ✅ Best suited ✅ Still valid but verbose
Multiple values mapping ❌ Repetitive code ✅ More concise syntax
Type-based checks ❌ Not supported ✅ Works well
Complex conditions ❌ Not possible ✅ Supports relational and logical patterns
Readability ❌ Verbose ✅ More concise and expressive

Conclusion

The switch case in C# has evolved significantly, from a rigid control flow structure to a flexible and expressive pattern-matching tool. While the traditional switch case is still useful for simple value-based comparisons, the modern switch case with pattern matching provides more concise, readable, and powerful solutions for complex logic. Understanding both approaches allows you to write cleaner, more efficient C# tutorial in C# code.

This C# tutorial aimed to highlight the differences between traditional and modern switch case techniques. By leveraging modern features, developers can improve code maintainability and readability. Happy coding! 🚀

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
yusmaikel_cabrera_575cfda profile image
Yusmaikel Cabrera

Great !!!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay