[C#] Writing Concise Conditional Logic with Switch Expressions

Introduced in C# 8.0, Switch Expressions allow for more concise and intuitive coding compared to traditional switch statements.

While traditional switch statements were “control structures (statements),” switch expressions are “expressions,” meaning they can assign results directly to variables or return them as method values. This significantly reduces lines of code and improves readability.

In this article, I will explain the basic syntax and usage of switch expressions using code that determines the drive type using the System.IO.DriveType enum.

目次

Table of Contents

  1. Implementation Example: Determining Drive Type
  2. Explanation and Key Points
  3. Summary

Implementation Example: Determining Drive Type

Below is a program that retrieves the corresponding name as a string based on the specified drive type (enum).

using System;
using System.IO;

namespace SwitchExpressionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Drive type to check (e.g., Network Drive)
            DriveType currentDrive = DriveType.Network;

            // Logic using switch expression
            // Can assign result directly to variable 'driveInfo'
            string driveInfo = currentDrive switch
            {
                DriveType.Fixed => "Fixed Disk (HDD/SSD)",
                DriveType.Network => "Network Drive",
                DriveType.Removable => "Removable Disk (USB, etc.)",
                DriveType.CDRom => "Optical Disc Drive",
                DriveType.Ram => "RAM Disk",
                // Underscore (_) is the "discard pattern" equivalent to default
                _ => "Other Drive"
            };

            Console.WriteLine($"Result: {driveInfo}");
            
            // Ref: Example of returning directly from a method
            Console.WriteLine(GetStatusMessage(200));
        }

        // Switch expressions are very easy to use as method return values
        static string GetStatusMessage(int statusCode) => statusCode switch
        {
            200 => "Success",
            404 => "Not Found",
            500 => "Server Error",
            _ => "Unknown Status"
        };
    }
}

Explanation and Key Points

1. Basic Syntax Changes

Keywords like case : and break; are no longer needed. Instead, the arrow operator => is used.

  • Traditional: case DriveType.Fixed: result = "Fixed"; break;
  • Switch Expression: DriveType.Fixed => "Fixed",

Each arm (branch) is separated by a comma ,.

2. default Case (Discard Pattern)

Instead of the traditional default: label, an underscore _ is used. This is called the Discard Pattern and defines the logic when no other conditions match. Since switch expressions must return a value, you are required to either cover all possible patterns or provide this discard pattern.

3. Usage as an Expression

As seen in the GetStatusMessage method in the example, switch expressions return a value as a result of evaluation. By combining this with method definitions using => (expression-bodied members), you can create very compact methods.


Summary

By using switch expressions, you can write conditional logic in a declarative and simple way.

  • Syntax: variable switch { pattern => value, _ => default_value };
  • Benefits: Reduced lines of code, prevention of missing break statements, and direct assignment to variables.

In C# 8.0 and later environments, it is recommended to actively use switch expressions over traditional switch statements for simple value conversion and mapping tasks.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次