How can I retrieve Enum from char value?

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

There are multiple ways to get the enum Name from value.

string name =   ((MaritalStatus)'S').ToString();
string enumName =  Enum.GetName(typeof(MaritalStatus), 'S');

In C# 6.0 you can use nameof


I guess found One solution for that:

   (MaritalStatus)Enum.ToObject(typeof(MaritalStatus), 'S')

It gets me MaritalStatus.Single

Enum.ToObject(enumType, byte) is the signature.

Tags:

C#

Enums

Parsing