Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    {
        Unknown,
        iPhone,
        Andriod,
        WindowsPhone7,
        Palm
    }

    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.

Edit: Adjusted one of the enums to not be defined with integers. So I can guarantee that 0 will always be the case but Unknown will always be the correct text... I guess I could use the same example as the T(0) but do another parse on the text "Unknown".

like image 907
Kelsey Avatar asked Apr 16 '10 21:04

Kelsey


People also ask

Can you convert string to Enum?

IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

What is the method to convert an Enum type to a string type?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can we convert string to Enum in Java?

You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.

How do you use generic enums?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation.


1 Answers

Use this, assuming that Unknown is always the 0 value.

public static T ConvertToEnum<T>(this string value) where T : new()
{
    if( !typeof(T).IsEnum )
        throw new NotSupportedException( "T must be an Enum" );

    try
    {
        return (T)Enum.Parse(typeof(T), value);
    }
    catch
    {
        return default(T); // equivalent to (T)0
        //return (T)Enum.Parse(typeof(T), "Unknown"));
    }
}

Usage:

EnumType2 a = "Cat".ConvertToEnum<EnumType2>(); 
EnumType2 b = "Person".ConvertToEnum<EnumType2>(); // Unknown

EDIT By OP (Kelsey): Your answer lead me to the correct answer so I thought I would include it here:

public static T ConvertTo<T>(this string value)
{
    T returnValue = (T)(Enum.Parse(typeof(T), "Unknown", true));
    if ((string.IsNullOrEmpty(value) == false) && 
        (typeof(T).IsEnum))
    {
        try { returnValue = (T)(Enum.Parse(typeof(T), value, true)); }
        catch { }
    }
    return returnValue;
}
like image 112
chilltemp Avatar answered Oct 09 '22 12:10

chilltemp