OT: Convert to Enum from int or char

Recently I answered a question on Stack Overflow where someone was interested in mapping a character to an Enum value.  Obviously this isn’t something naturally possible with Enums, so I proposed the following solution.  I’ve previously blogged about a generic approach to working with Strings and Enums here.

If we represented the Enum by using the ASCII value, we can define the Enum like so:

public enum Fruit : int
{
    Apple   = 65,  //’A’
    Banana = 66,  //’B’
    Cherry  = 67   //’C’
}

So, in order to convert ‘A’ –> Fruit.Apple we can convert the char (‘A’) to the int value and then cast it to the Enum.  I’ve also included another method using a similar approach to convert from an integer (e.g. 65 –> Fruit.Apple) to the desired Enum value.

    public static class EnumConverter<T> where T : struct
    {
        public static T FromIntToEnum(int intToConvert, out bool success)
        {
            try
            {
                if (Enum.IsDefined(typeof(T), intToConvert))
                {
                    success = true;
                    return (T)Enum.ToObject(typeof(T), intToConvert);
                }
            }
            catch (ArgumentException ex)
            {
                // Use your own Exception Management Here
            }
            catch (InvalidCastException ex)
            {
                // Use your own Exception Management Here
            }
            success = false;
            return default(T);
        }

        public static T ToEnum(char charToConvert, out bool success)
        {
            try
            {               
                int intValue = Convert.ToInt32(charToConvert);               
                if (Enum.IsDefined(typeof(T), intValue))
                {
                    success = true;
                    return (T)Enum.ToObject(typeof(T), intValue);
                }
            }
            catch (ArgumentException ex)
            {
                // Use your own Exception Management Here
            }
            catch (InvalidCastException ex)
            {
                // Use your own Exception Management Here
            }
            success = false;
            return default(T);
        }
    }

Here’s a possible usage scenario:

bool success = false;
Fruit selected = EnumConverter<Fruit>.ToEnum(‘A’, out success);
if (success)
{
     // good to go (returns Fruit.Apple)

}

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One thought on “OT: Convert to Enum from int or char”