Will
Will

Reputation: 10431

Get underlying/derived type of enum?

How can you get the underlying/derived Type(byte, short, int, etc) of an enum?

Upvotes: 15

Views: 5710

Answers (3)

Mike Nakis
Mike Nakis

Reputation: 62129

Method 1:

Type underlyingType = System.Enum.GetUnderlyingType(typeof(MyEnum));

Method 2:

Type underlyingType = typeof(MyEnum).GetEnumUnderlyingType();

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45068

using System;

class Program
{
    enum IntEnum : int { A }

    static void Main(string[] args)
    {
        var intEnum = IntEnum.A;

        Console.WriteLine(intEnum.GetType().GetEnumUnderlyingType());

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }       
}

Upvotes: 5

BrokenGlass
BrokenGlass

Reputation: 161002

You are looking for Enum.GetUnderlyingType(enumType);

Sample from MSDN:

static object GetAsUnderlyingType(Enum enval)
{
    Type entype = enval.GetType();

    Type undertype = Enum.GetUnderlyingType(entype);

    return Convert.ChangeType(enval, undertype);
}

Upvotes: 22

Related Questions