Why is an if statement working but not a switch statement

  • A+

Title is terrible, but I wasn't too sure what to put.

I'm trying to create Switch Statement using the char index of a string and an Enum using this wrapper to get the value of the selected enum from a Description, it pretty much allows you to store a string to an enum value.

Here is my if statement

if (msgComingFromFoo[1] == Convert.ToChar(Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString())) {     //foo } 

and here is my Switch statement

switch (msgComingFromFoo[1]) {     case Convert.ToChar(Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString()):         break; } 

Why is it accepting the if statement and not the switch statement?

I tried converting it to a char since I'm selected an index from a string, but unfortunately i didn't work.


Here is the Message.Code Enum

public class Message {     public enum Code     {         [Description("A")]         FOO_TRIGGER_SIGNAL     } } 

As you can see, I need the Description assigned to the enun not the enum value that is 0, using Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString() from the mentioned wrapper returns A not 0


You cannot have expressions in the case, but you can in the switch, so this will work:

switch (ConvertToMessageCode(msgComingFromFoo[1])) {     case Message.Code.FOO_TRIGGER_SIGNAL:         break; } 

Where you will need to write ConvertToMessageCode to do the necessary conversion to the Message.Code enum. ConvertToMessageCode just abstracts the necessary conversion details, you may find you do not need a separate method, but can make do with inline code in the switch statement, e.g., a cast.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: