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"
Use the
_discard symbol with thewhenkeyword followed by an equality expression to matchvalueon a non-constant value:Thanks to this Q&A: How To Perform Pattern Matching With Switch For Non-Constant String Value?