Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve Enum from char value?

Tags:

c#

enums

parsing

I have the following enum

public enum MaritalStatus
{
    Married = 'M',
    Widow = 'W',
    Widower = 'R',
    Single='S'
}

In one function I have for exp: 'S' , and I need to have MaritalStatus.Single.

How can I get the enum from the character value? For string I found this solution, but it gets exception for Char.

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
like image 646
Sara N Avatar asked Oct 26 '16 06:10

Sara N


1 Answers

The enum values, though defined with chars actually equal to the int representation of that char. It is as if you defined it as following:

public enum MaritalStatus
{
    Married = 77,
    Widow = 87,
    Widower = 82,
    Single=83
} 

Convert char to int and then assign to the enum:

int m = 'M'; // char of `M` equals to 77
MaritalStatus status = (MaritalStatus)m;  

Console.WriteLine(status == MaritalStatus.Married); // True
Console.WriteLine(status == MaritalStatus.Single); // False

After playing with it a bit and putting it into a one liner I see that even the conversion to an int is not needed. All you need is to cast as the enum:

MaritalStatus status = (MaritalStatus)'M'; // MaritalStatus.Married
like image 74
Gilad Green Avatar answered Oct 16 '22 15:10

Gilad Green