TIL: Tuples and Pattern Matching in C# switch Statements

TIL. abbreviation for today I learned
used in writing, for example on social media, before giving interesting new information

It may not happen all the time, but every now and then there are cases where a certain outcome is expected due to two or more variables. For example the help or validation text for variable min and max values. Until now I have solved this with these monstrous “if – else if” nestings:

var helpText1 = "Please enter any number of values";

if (min > 0 && max > 0)
{
    if (min == max)
    {
        helpText1 = $"Please enter exactly {max} values";
    }
    else
    {
        helpText1 = $"Please enter between {min} and {max} values";
    }
}
else if (min > 0 && max == 0)
{
    helpText1 = $"Please enter at least {min} values";
}
else if (min == 0 && max > 0)
{
    helpText1 = $"Please enter a maximum of {max} values";
}

But today I learned that thanks to C# 8.0 you can use tuple pattern matching, and thanks to C# 9.0 pattern matching has been extended even further. Therefore, the above can now be easily mapped beautifully like this:

var helpText2 = (min, max, min == max) switch
{
    (0, > 0, _) => $"Please enter a maximum of {max} values",
    ( > 0, > 0, false) => $"Please enter between {min} and {max} values",
    ( > 0, > 0, true) => $"Please exactly {max} values",
    ( > 0, 0, _) => $"Please enter at least {min} values",
    _ => "Please enter any number of values"
};

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *