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