Unbox Enum as an 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.

Unboxing an enum when the underlying type is known
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:

Unboxing an enum when the underlying type is not known
    /// <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.

This entry was posted in C#, Migrated, Programming. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

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