Is there a cleaner way to get the char value of an enum in C#.
public enum DivisionStatus { None = 'N', Active = 'A', Inactive = 'I', Waitlist = 'W' } string status = Enums.DivisionStatus.Active.ToString()[0].ToString(); // "A"
First of all, YES, we can assign an Enum to something else, a char !
Using an enum means you can only have one of those three values or it won't compile. Using strings means your code has to constantly check for equality during runtime - so it becomes bloated, slower and error prone.
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
Just cast the value:
char status = (char)Enums.DivisionStatus.Active;
Note that this will use the value instead of the identifier. The Enums.DivisionStatus.Active
value is the character code of 'A'
, as that is the value that you have defined.
Using the value directly is faster than looking up the identifier for the value.
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