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
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.
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.
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.
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.
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.
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