My name is Edward Tanguay. I'm an American software and web developer living and working in Berlin, Germany.
C# CODE EXAMPLE created on Friday, July 02, 2010 permalink
Generic method to case-insensitively convert a string to any enum
This generic static method takes an enum type and a string and converts it, ignoring case, and if the string is invalid, it will return the first (default) item in the enum collection. I'm returning the default value in a catch since IsDefined doesn't have an ignoreCase parameter, but there are more elegant ways to do this, especially in C#4 .
using System;

namespace TestEnum2934234
{
    class Program
    {
        static void Main(string[] args)
        {
            LessonStatus lessonStatus = StringHelpers.ConvertStringToEnum<LessonStatus>("pxrepared");
            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)
        {
            try
            {
                return (T)Enum.Parse(typeof(T), text, true);
            }
            catch (ArgumentException ex)
            {
                return default(T);
            }
        }
    }

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

    public enum ReportStatus
    {
        Draft,
        Revising,
        Finished
    }
}
need markup?