ILearnable .Net

February 20, 2014

Working with Enums

Filed under: Uncategorized — andreakn @ 15:14

Enums are like the small tokens you can use instead of real coins in shopping carts, lockers etc. They really have a very limited use, can always be replaced by something more valuable which also gets the job done, but sometimes it’s nice to have them. even if they are the bastard child of int and object.

when converting to/from different enum types and values / strings as one typically has to do when down the enum-road here’s a helper class which sweetens the taste a bit

 public class EnumMeta<TEnum>
    {
        public EnumMeta()
        {
            var type = typeof (TEnum);
            if (!type.IsEnum)
            {
                throw new ArgumentException(string.Format("The type {0} is not an Enum, which is sort of a big deal around here.", type));
            }
        }

        public TEnum Convert(object stupidValue)
        {
            try
            {
                return DoConvert((dynamic)stupidValue);
            }
            catch (Exception)
            {
                throw new ArgumentException(string.Format("One does not simply convert value '{0}' ({1}) to type {2}", stupidValue, stupidValue.GetType(), typeof(TEnum)));
            }
        }

        private static TEnum DoConvert(byte value)
        {
            return (TEnum) Enum.ToObject(typeof (TEnum), value);
        }

        private static TEnum DoConvert(int value)
        {
            return (TEnum) Enum.ToObject(typeof(TEnum), value);
        }

        private static TEnum DoConvert(string value)
        {
            return (TEnum) Enum.Parse(typeof(TEnum), value);
        }

        private static TEnum DoConvert(object value)
        {
            return DoConvert((int)value);
        }

        public IEnumerable<TEnum> GetValues()
        {
            return Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
        }
    }
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: