OdeToCode IC Logo

Switch Expressions are the Best Feature of C# 8

Monday, January 6, 2020

I thought <Nullable>enable</Nullalble> would be the star of the C# 8 show by now, but in day to day work I'm finding that switch expressions are stealing the show.

Size = 1 + Operands.Size;
OpCode = Bits.BottomFive(memory.Bytes[0]);

Operation = OpCode switch
    0x01 => new Operation(nameof(JE), JE, hasBranch: true),
    0x0A => new Operation(nameof(TestAttr), TestAttr, hasBranch: true),
    0x0F => new Operation(nameof(LoadW), LoadW, hasStore: true),
    0x09 => new Operation(nameof(And), And, hasStore: true),
    0x10 => new Operation(nameof(LoadB), LoadB, hasStore: true),
    0x14 => new Operation(nameof(Add), Add, hasStore: true),
    0x0D => new Operation(nameof(StoreB), StoreB),
    _ => throw new InvalidOperationException($"Unknown OP2 opcode {OpCode:X}")

I was never a fan of switch statements, but switch expressions have the ability to reduce nasty, nested, cyclomatically complex code into a tabular, declarative display of elegant simplicity.

Another example:

var instruction = memory.Bytes[0] switch
    0xBE => DecodeExt(memory),
    var v when Bits.SevenSixSet(v) => DecodeVar(memory),
    var v when Bits.SevenSet(v) => DecodeShort(memory),
    _ => DecodeLong(memory)