Why this swich statement do not work, gives error:
A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type
Code:
switch (btn.BackColor)
{
case Color.Green:
break;
case Color.Red:
break;
case Color.Gray:
break;
}
For more information, see Patterns. In C# 6 and earlier, you use the switch statement with the following limitations: A match expression must be of one of the following types: char, string, bool, an integral numeric type, or an enum type. Only constant expressions are allowed in case labels.
Basic switch with defaultA switch statement runs the first case equal to the condition expression. The cases are evaluated from top to bottom, stopping when a case succeeds. If no case matches and there is a default case, its statements are executed.
The error in in itself is self explanatory. it it telling you that switch expression must be ofone of these types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. or as the C# language specification suggests
exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types.
And you can see that BackColor is returning your a type here and it is not satisfying any of the above rules, hence the error.
you can do it like this
switch (btn.BackColor.Name)
{
case "Green":
break;
case "Red":
break;
case "Gray":
break;
}
The problem is you can't use a Color
in a switch
statement. It must be one of the following types, a nullable version of one of the types, or or convertible to one of these types: sbyte
, byte
, short
, ushort
, int
, uint
, long
, ulong
, char
, string
From the C# language spec, 8.7.2:
• Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types.
In your case, you could work around this by using strings, or just using a set of if
/else
statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With