Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing string to match enum value

Tags:

c#

enums

If I have an enum of char's

public enum Action
{
    None,
    Address = 'A',
    Amendment = 'C',
    Normal = 'N'
}

What is the best way to parse a single character string to match the corresponding enum char and match None if not found. TryParse matches the Name and not the value.

For instance if the string I had were "C" I would want to get Action.Amendement

Thanks in advance

like image 374
m4rc Avatar asked Mar 07 '12 08:03

m4rc


People also ask

How do you find the enum value of a string?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do I convert string to enum?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

How do you convert a string value to a specific enum type in C#?

To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.

Can string be used with enum?

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. Specify the type after enum name as : type .


2 Answers

char c = 'C'; // existent value
var action = Enum.GetValues(typeof(Action)).Cast<Action>().FirstOrDefault(a => (char)a == c);
// action = Action.Amendment

and:

char c = 'X'; // non existent value
var action = Enum.GetValues(typeof(Action)).Cast<Action>().FirstOrDefault(a => (char)a == c);
// action = Action.None
like image 153
Darin Dimitrov Avatar answered Oct 11 '22 17:10

Darin Dimitrov


Just cast it :

Action f = (Action)'C';

If you had a string and were positive it was at least 1 character you can do:

Action f = (Action)"C"[0];
like image 23
Oskar Kjellin Avatar answered Oct 11 '22 18:10

Oskar Kjellin