Is there a better way to create a generic convert string to enum method or enum extension?

Posted by Kelsey on Stack Overflow See other posts from Stack Overflow or by Kelsey
Published on 2010-04-16T21:04:57Z Indexed on 2010/04/16 21:13 UTC
Read the original article Hit count: 458

Filed under:
|
|

I have the following methods in an enum helper class (I have simplified it for the purpose of the question):

static class EnumHelper
{
    public enum EnumType1 : int
    {
        Unknown = 0,
        Yes = 1,
        No = 2
    }

    public enum EnumType2 : int
    {
        Unknown = 0,
        Dog = 1,
        Cat = 2,
        Bird = 3
    }

    public enum EnumType3 : int
    {
        Unknown = 0,
        iPhone = 1,
        Andriod = 2,
        WindowsPhone7 = 3,
        Palm = 4
    }

    public static EnumType1 ConvertToEnumType1(string value)
    {
        return (string.IsNullOrEmpty(value)) ?
            EnumType1.Unknown :
            (EnumType1)(Enum.Parse(typeof(EnumType1), value, true));
    }

    public static EnumType2 ConvertToEnumType2(string value)
    {
        return (string.IsNullOrEmpty(value)) ?
            EnumType2.Unknown :
            (EnumType2)(Enum.Parse(typeof(EnumType2), value, true));
    }

    public static EnumType3 ConvertToEnumType3(string value)
    {
        return (string.IsNullOrEmpty(value)) ?
            EnumType3.Unknown :
            (EnumType3)(Enum.Parse(typeof(EnumType3), value, true));
    }
}

So the question here is, can I trim this down to an Enum extension method or maybe some type of single method that can handle any type. I have found some examples to do so with basic enums but the difference in my example is all the enums have the Unknown item that I need returned if the string is null or empty (if no match is found I want it to fail).

Looking for something like the following maybe:

EnumType1 value = EnumType1.Convert("Yes");
// or
EnumType1 value = EnumHelper.Convert(EnumType1, "Yes");

One function to do it all... how to handle the Unknown element is the part that I am hung up on.

© Stack Overflow or respective owner

Related posts about c#

Related posts about enums