Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum value to string

Tags:

c#

Does anyone know how to get enum values to string?

example:

private static void PullReviews(string action, HttpContext context) {     switch (action)     {         case ProductReviewType.Good.ToString():             PullGoodReviews(context);             break;         case ProductReviewType.Bad.ToString():             PullBadReviews(context);             break;     } } 

Edit:

When trying to use ToString(); the compiler complains because the case statement is expecting a constant. I also know that ToString() is is striked out with a line in intellisense

like image 397
PositiveGuy Avatar asked Jun 25 '10 18:06

PositiveGuy


People also ask

Can enum have string values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Can I convert enum to string C++?

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.

Is enum string Java?

The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.


1 Answers

Yes, you can use .ToString() to get a string value for an enum, however you can't use .ToString() in a switch statement. Switch statements need constant expressions, and .ToString() does not evaluate until runtime, so the compiler will throw an error.

To get the behavior you want, with a little change in the approach, you can use enum.Parse() to convert the action string to an enum value, and switch on that enum value instead. As of .NET 4 you can use Enum.TryParse() and do the error checking and handling upfront, rather than in the switch body.

If it were me, I'd parse the string to an enum value and switch on that, rather than switching on the string.

private static void PullReviews(string action, HttpContext context) {     ProductReviewType review;      //there is an optional boolean flag to specify ignore case     if(!Enum.TryParse(action,out review))     {        //throw bad enum parse     }       switch (review)     {         case ProductReviewType.Good:             PullGoodReviews(context);             break;         case ProductReviewType.Bad:             PullBadReviews(context);             break;         default:             //throw unhandled enum type     } } 
like image 63
Alan Avatar answered Sep 20 '22 09:09

Alan