Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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;
 }
like image 343
NoviceToDotNet Avatar asked Aug 16 '13 17:08

NoviceToDotNet


People also ask

Can we use expression in Switch Case C#?

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.

Does switch case go in order?

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.


2 Answers

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;
}
like image 198
Ehsan Avatar answered Oct 25 '22 12:10

Ehsan


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.

like image 38
Reed Copsey Avatar answered Oct 25 '22 12:10

Reed Copsey