C#C
C#3y ago
__dil__

✅ Switch pattern matching with integers

Is this a valid/idiomatic way to use pattern matching to compare integers?

    public static double SuccessRate(int speed) =>
        speed switch
        {
            0 => 0.0,
            < 5 => 1.0,
            < 9 => 0.9,
            9 => 0.8,
            10 => 0.77,
            _ => throw new Exception($"Expected speed between 0 and 10, got `{speed}`")
        };


One thing bugging me in particular is: are the arms checked in the order they were written, or is the order not guaranteed?

If the order is not guaranteed, then obviously the code above does not work.
Was this page helpful?