Will
Will

Reputation: 10411

Get underlying/derived type of enum?

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

Upvotes: 15

Views: 5704

Answers (2)

Grant Thomas
Grant Thomas

Reputation: 45083

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: 160852

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