Unbox Enum as Integral Value

I needed a way to get the integral value of an System.Enum that is boxed. The solution wasn't immediately obvious after my experimentation mainly because:

  • My enum was derived from byte (and I was trying to cast it to an int).
  • My .Net jitsu wasn't up to scratch.

Lucky thanks to a friendly guy called Guffa I managed to create generic solution.

As it turns out you can unbox an enum value to its base type. As such the following can be unboxed to an uint.


struct FoolishStruct : uint
{
   Gluttony,
   Pride,
   Jealousy
}

object sinner = FoolishStruct.Gluttony;
uint value = (uint)sinner; // This works.

This gave me the necessary knowledge to hash out the following solution:


    /// <summary>
/// Gets the integral value of an enum. /// </summary> /// <param name="value">The enum to get the integral value of.</param> /// <returns></returns> public static T ToIntegral<T>(this object value) { if(object.ReferenceEquals(value, null)) throw new ArgumentNullException("value"); Type rootType = value.GetType(); if (!rootType.IsEnum) throw new ArgumentOutOfRangeException("value", "value must be a boxed enum."); Type t = Enum.GetUnderlyingType(rootType); switch (t.Name.ToUpperInvariant()) { case "SBYTE": return (T)Convert.ChangeType((sbyte) value, typeof(T)); case "BYTE": return (T) Convert.ChangeType((byte) value, typeof(T)); case "INT16": return (T) Convert.ChangeType((Int16) value, typeof(T)); case "UINT16": return (T) Convert.ChangeType((UInt16) value, typeof(T)); case "INT32": return (T) Convert.ChangeType((Int32) value, typeof(T)); case "UINT32": return (T) Convert.ChangeType((UInt32) value, typeof(T)); case "INT64": return (T) Convert.ChangeType((Int64) value, typeof(T)); case "UINT64": return (T) Convert.ChangeType((UInt64) value, typeof(T)); default: throw new NotSupportedException(); } }

HTH.

posted @ Tuesday, April 14, 2009 7:10 AM

Print
«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345