How to use a switch expression to match a value where it equals another non-constant value

60 views Asked by At

I want to write a method that converts a WPF System.Windows.FontWeight property to its equivalent CSS value using C#11. A switch expression seems the most appropriate construct. Here's my attempt:

    string ToCssValue(FontWeight value) => value switch
    {
        FontWeights.Bold => "bold",
        FontWeights.ExtraBold => "bolder",
        FontWeights.Normal => "normal",
        FontWeights.Light => "lighter",
        _ => value.ToOpenTypeWeight().ToString(CultureInfo.InvariantCulture),
    };

However, I get an error on FontWeights.Bold: A constant value of type 'FontWeight' is expected. This is happening because FontWeights.Bold is a reference to a specific instance of the FontWeight struct. Since FontWeight is a Value Type I though the switch expression would be smart enough to know I mean to switch value on FontWeights.Bold using the default equality, which is 'by value' for value types. However, it appears not.

How can I use a switch expression to match the value of variable with another non-constant value using default equality, or in other words, how do I "switch on value where it equals FontWeights.Bold"

1

There are 1 answers

1
Dan Stevens On BEST ANSWER

Use the _ discard symbol with the when keyword followed by an equality expression to match value on a non-constant value:

    string ToCssValue(FontWeight value) => value switch
    {
        _ when value == FontWeights.Bold => "bold",
        _ when value == FontWeights.ExtraBold => "bolder",
        _ when value == FontWeights.Normal => "normal",
        _ when value == FontWeights.Light => "lighter",
        _ => value.ToOpenTypeWeight().ToString(CultureInfo.InvariantCulture),
    };

Thanks to this Q&A: How To Perform Pattern Matching With Switch For Non-Constant String Value?