Skip to content

Switch expressions C# 8.0code reductionreadability

A switch designed to return values directly within a method.

Producing a value from some other value is a very common pattern and one that switch is often used for. Unfortunately using switch statements directly involve declaring the variable then setting it and breaking inside each case is verbose and error-prone.

This can be somewhat mitigated by simply wrapping the switch statement in a method of its own so you can take full advantage of the return keyword from each case thus avoiding the need to declare and set the variable and do away with all break statements.

In C# 8 this is no longer necessary as the new expression form of switch produces a value directly without wrapping it in a new function.

Code ​

csharp
var sysInfo = new SysInfo();
GetNativeSystemInfo(ref sysInfo);

var procArch = sysInfo.ProcessorArchitecture switch
{
    0 => "x86",
    6 => "IA64",
    9 => "x64",
    _ => string.Empty
};
csharp
var sysInfo = new SysInfo();
GetNativeSystemInfo(ref sysInfo);

var procArch = GetPlatform(sysInfo);

string GetPlatform(SysInfo sysInfo)
{
    switch (sysInfo.ProcessorArchitecture)
    {
        case 0: return "x86";
        case 6: return "IA64";
        case 9: return "x64";
        default: return string.Empty;
    }
}

Notes ​

  • If no arm matches at runtime a SwitchExpressionException is thrown, and the compiler warns when the arms are not exhaustive

More information ​

Powered by Intracia