The switch expression or case label must be bool (or ...)

Why this swich statement does not work gives an error:

The switch expression or case label must be bool, char, string, integer, enum or the corresponding type with a null value

the code:

switch (btn.BackColor) { case Color.Green: break; case Color.Red: break; case Color.Gray: break; } 
+8
c #
source share
4 answers

The error itself is self-evident. it tells you that the switch expression must be one of the following types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. or since the C # language specification offers

only one user-defined implicit conversion (ยง6.4) must exist from the switch expression type: one of the following possible control types: sbyte, byte, short, ushort, int, uint, long, ulong, char, a string or a type with a null value corresponding to one of these types.

And you can see that BackColor returns your type here, and it does not satisfy any of the above rules, therefore, an error.

you can do it like this

 switch (btn.BackColor.Name) { case "Green": break; case "Red": break; case "Gray": break; } 
+6
source share

The problem is that you cannot use Color in a switch . It must be one of the following types: The NULL version of one of the types or is converted to one of the following types: sbyte , byte , short , ushort , int , uint , long , ulong , char , string

From the C # language specification, 8.7.2:

โ€ข Otherwise, only one user-defined implicit conversion (ยง6.4) must exist from the switch expression type: one of the following possible control types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string or type with a null value corresponding to one of these types.

In your case, you can get around this using strings, or just using a set of if / else .

+6
source share

You cannot enable BackColor because it is not an integral type.

You can include only integer types, enumerations (which are integer integer types), and characters and strings.

You need to find the BackColor property, which is unique (e.g. Name ) and enable it.

+3
source share

As other answers pointed out, System.Drawing.Color not a usable type in a switch . Color is an interesting type because it behaves like an enum in code, but that is because it has a static property for each System.Drawing.KnownColor , which is an enum type. So when you see Color.Green in your code, here is what the Color class does behind the scenes:

 public static Color Green { get { return new Color(KnownColor.Green); } } 

Knowing this bit of information, you can write your code like this to use the BackColor property in the switch:

 if (btn.BackColor.IsKnownColor) { switch (btn.BackColor.ToKnownColor()) { case KnownColor.Green: break; case KnownColor.Red: break; case KnownColor.Gray: break; } } else { // this would act as catch-all "default" for the switch since the BackColor isn't a predefined "Color" } 
+2
source share

All Articles