Search code examples
c#parsingenumschar

How can I retrieve Enum from char value?


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);

Solution

  • 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.