Dan Rigsby - Coding Up Style

Developer.Speaker.Blogger

Missing static generic alternatives in Enum class?

Posted by Dan Rigsby on December 16th, 2007

I ran into an issue earlier this week while working with a generic class where one of the template parameters would represent a possible enum value.  (Basically we have different enum lists representing different actions). You cant use a “where” clause for the enum class.  So how would take a string or an int and cast it back to the type of enum defined in the template parameter? I had thought the static Enum class would provide new methods such as Enum.ToObject<T> and Enum.Parse<T> to match the non-generic methods, but they weren’t there.  My needs here were pretty specific, but I soon realized that every time I cast an into to an enum I had to cast the result of Enum.ToObject(int) to the enum type.  Why wouldn’t they have implemented generic methods for these common task?  Generics were built for stuff like this.

Here is a basic EnumUtilities class I built to work around this issue and to assist with enum casting in the future:

using System;
namespace ININ.Common
{
    /// <summary>   
    /// Utilities to assist with enums.   
    /// </summary>   
    public static class EnumUtilities
    {
        /// <summary>       
        /// Parses the enum.       
        /// </summary>       
        /// <typeparam name=”T”></typeparam>       
        /// <param name=”name”>The name.</param>       
        /// <returns></returns>       
        public static T ParseEnum<T>(
            string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new NullArguementException("name is null or an empty string.");
            }
            return (T)Enum.Parse(typeof(T), name);
        }        

        /// <summary>       
        /// Parses the enum ID to the enum type.       
        /// </summary>       
        /// <typeparam name=”T”></typeparam>       
        /// <param name=”i”>The i.</param>       
        /// <returns></returns>       
        public static T ToObject<T>(
            int i)
        {
            return (T)Enum.ToObject(typeof(T), i);
        }
    }
}

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>