© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
44 replies
__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}`")
        };
    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.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Using Params with Pattern Matching Switch statement
C#CC# / help
2y ago
❔ How to replace string.IsNullOrWhiteSpace() with pattern matching?
C#CC# / help
3y ago
❔ Pattern matching on multiple cases with the same-typed members
C#CC# / help
3y ago
Proper syntax for pattern matching with less than greater than
C#CC# / help
4y ago