Search code examples
c#pattern-matchingidioms.net-5readability

Is there a more C# 9 / .NET 5 Idiomatic Way to Express If/Else when Testing Ranges? (Pattern Matching or newer C# features)


Just had to write some code for a project today that is really close to this:

private static string CreateColorFromPercentage(double percentage, bool isPrimaryGroup)
{
    if (isPrimaryGroup)
    {
        if (percentage >= 97.0)
        {
            return "#000000"; // black
        }
        else if (percentage > 80.0)
        {
            return "#FF0000"; // red
        }
        else
        {
            return "#FFA500"; // orange
        }
    }
    else
    {
        if (percentage > 97.5)
        {
            return "#000000"; // black
        }
        else if (percentage > 80.0)
        {
            return "#FFA500"; // orange
        }
        else
        {
            return "#008000"; // green
        }
    }
}

Is there a more C# 9 / .NET 5 Idiomatic Way to Express If/Else when Testing Ranges? Resharper is already telling me to shorten up / drop some of the else statements. Is there a more "grid" like human-readable version of this? Better way to express the same intent but have it read like 6 simple conditions. Thanks.


Solution

  • With .NET 5 you should be able to use pattern matching like in this example:

    static string CreateColorFromPercentage(double percentage, bool isPrimaryGroup) {
        return (percentage, isPrimaryGroup) switch {
            (>= 97.0, true)  => "#000000",
            (> 80.0,  true)  => "#FF0000",
            (_,       true)  => "#FFA500",
            (>= 97.5, false) => "#000000",
            (> 80.0,  false) => "#FFA500",
            (_,       false) => "#008000"
        };
    }