Given the code below:
static void Main()
{
Console.WriteLine(typeof(MyEnum).BaseType.FullName);
}
enum MyEnum : ushort
{
One = 1,
Two = 2
}
It outputs System.Enum, which means the colon here has nothing to do with inheritance, and it just specifies the basic type of the enum, am I right?
But if I change my code as follows:
enum MyEnum : UInt16
{
One = 1,
Two = 2
}
I would get a compilation error. Why? Aren’t UInt16 and ushort the same?
You are correct that reflection doesn’t report that an enum inherits the base type, which the specification calls the “underlying type”. You can find it using
Enum.GetUnderlyingTypeinstead.The type named by
ushortandSystem.UInt16are precisely the same.However, the syntax of
enumdoes not call for a type. Instead it calls for one of a limited set of keywords, which control the underlying type. WhileSystem.UInt16is a valid underlying type, it is not one of the keywords which the C# grammar permits to appear in that location.Quoting the grammar: