Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an if statement working but not a switch statement

I'm trying to create a 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? I tried converting it to a char since I'm selecting an index from a string, but unfortunately it didn't work.

Update:

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 enum not the enum value that is 0. Using Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString() from the mentioned wrapper returns A not 0


Error:

A Constant Value Is Expected

like image 616
traveler3468 Avatar asked Jul 31 '18 14:07

traveler3468


People also ask

What is the difference between if statement and switch statement?

The if statement evaluates integer, character, pointer or floating-point type or boolean type. On the other hand, switch statement evaluates only character or a integer datatype.

Is an if statement a switch statement?

An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

Which is better to use if statement or switch statement?

A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.

Why do we use a switch instead of an IF-ELSE statement?

When you use switch to check a value for multiple possible results, that value will only be read once, whereas if you use if it will be read multiple times. This becomes more important when you start using function calls, because some of these can be slow.


1 Answers

You cannot have expressions in the case (prior to C# 7), 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 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.

like image 75
Polyfun Avatar answered Oct 14 '22 00:10

Polyfun