Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the string value of a C# enum value in a case statement?

Tags:

string

c#

enums

I have defined a C# enum as

public enum ORDER {     ...     unknown,     partial01,     partial12,     partial23, } 

and can use its value as a string as in:

            string ss = ORDER.partial01.ToString(); 

However when I try to use it in a case statement it fails to compile:

string value = ... switch (value) {     case null:         break;     case "s":         // OK         break;     case ORDER.partial01.ToString():         // compiler throws "a constant value is expected"          break;   ... 

I thought enums were constants. How do I get around this?

(I cannot parse the value into an enum as some of the values are outside the range)

like image 448
peter.murray.rust Avatar asked Aug 13 '09 16:08

peter.murray.rust


People also ask

How many ways can you read a string in C?

C provides two basic ways to read and write strings. input/output functions, scanf/fscanf and printf/fprintf. Second, we can use a special set of string-only functions, get string (gets/fgets) and put string ( puts/fputs ).

Can we take string in C?

We can take string input in C using scanf(“%s”, str). But, it accepts string only until it finds the first space. There are 4 methods by which the C program accepts a string with space in the form of user input.

Can you pass a string by value in C?

C doesn't have strings as first class values; you need to use strcpy() to assign strings.

Does C have string data type?

Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.


1 Answers

Since C# 6, you can use: case nameof(SomeEnum.SomeValue):

Nameof is evaluated at compile time, simply to a string that matches the (unqualified) name of the given variable, type, or member. Naturally, it changes right along should you ever rename the enum option name.

like image 113
Timo Avatar answered Oct 15 '22 18:10

Timo