Reputation: 10431
How can you get the underlying/derived Type(byte, short, int, etc) of an enum?
Upvotes: 15
Views: 5710
Reputation: 62129
Method 1:
Type underlyingType = System.Enum.GetUnderlyingType(typeof(MyEnum));
Method 2:
Type underlyingType = typeof(MyEnum).GetEnumUnderlyingType();
Upvotes: 0
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
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