Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better Way To Get Char Enum

Tags:

c#

enums

char

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" 
like image 373
Mike Flynn Avatar asked Nov 14 '11 00:11

Mike Flynn


People also ask

Can enum have char value?

First of all, YES, we can assign an Enum to something else, a char !

Should I use enums or strings?

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.

How do you find the enum value of a list?

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.


1 Answers

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.

like image 182
Guffa Avatar answered Sep 23 '22 08:09

Guffa