Archives

Archives / 2006 / July
  • Generic Parse method on Enum - a solution

    David Findley writes about how he wishes we had a generic Parse method on the Enum class in .NET 2.0.

    Though I agree in principle, it's actually quite trivial to create a generic static class with a Parse method, which alleviates some of the pain.

    Here's my stab at it:

        public static class EnumUtil<T>
        {
            public static T Parse(string s)
            {
                return (T)Enum.Parse(typeof(T), s);
            }
        }


    Say we have the following enum:

        public enum Color
        {
            Black,
            White,
            Blue,
            Red,
            Green
        }

    We can now simply use the generic EnumUtil class as follows:

    Color c = EnumUtil<Color>.Parse("Black");

    I feel that this helper method doesn't actually warrant a class in its own right, so you may want to add it to one of your Util classes (if you happen to have a generic one!) instead.