views:

71

answers:

4

The following generic static method takes a string and returns an enum.

It nicely ignores case since I set the ignoreCase parameter to true.

However, I also want to test if the enum exists, but the enum.IsDefined method to do this doesn't seem to have an ignoreCase parameter.

How can I test if the enum is defined or not and at the same ignore case?

using System;

namespace TestEnum2934234
{
    class Program
    {
        static void Main(string[] args)
        {
            LessonStatus lessonStatus = StringHelpers.ConvertStringToEnum<LessonStatus>("prepared");
            ReportStatus reportStatus = StringHelpers.ConvertStringToEnum<ReportStatus>("finished");

            Console.WriteLine(lessonStatus.ToString());
            Console.WriteLine(reportStatus.ToString());
            Console.ReadLine();
        }
    }

    public static class StringHelpers
    {
        public static T ConvertStringToEnum<T>(string text)
        {
            if (Enum.IsDefined(typeof(T), text)) //does not have ignoreCase parameter
                return (T)Enum.Parse(typeof(T), text, true);
            else
                return default(T);
        }
    }

    public enum LessonStatus
    {
        Defined,
        Prepared,
        Practiced,
        Recorded
    }

    public enum ReportStatus
    {
        Draft,
        Revising,
        Finished
    }
}
+4  A: 
public enum MyEnum
{
    Bar,
    Foo
}

class Program
{
    static void Main(string[] args)
    {
        var containsFoo = Enum.GetNames(typeof(MyEnum)).Any(x => x.ToLower() == "foo");
        Console.WriteLine(containsFoo);
    }
}
Darin Dimitrov
+4  A: 

Along with @Darin's answer, in .NET 4.0, the Enum type now has a TryParse method:

MyEnum result;
Enum.TryParse("bar", true, out result);

The important thing to remember is that there is a fundamental difference in the behaviour of Parse vs TryParse. Parse methods will throw exceptions. TryParse methods will not. This is quite important to know if you are potentially trying to parse many items.

Matthew Abbott
+1  A: 

Use Enum.TryParse instead:

T val;

if(Enum.TryParse(text, true, out val))
    return val;
else 
    return default(T);
Justin Niessner
A: 
public static T ConvertStringToEnum<T>(string text)
{
    T returnVal;
    try
    {
        returnVal = (T) Enum.Parse( typeof(T), text, true );
    }
    catch( ArgumentException )
    {
        returnVal = default(T);
    }
    return returnVal;
}
maxwellb