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.GetUnderlyingType
instead.
The type named by ushort
and System.UInt16
are precisely the same.
However, the syntax of enum
does not call for a type. Instead it calls for one of a limited set of keywords, which control the underlying type. While System.UInt16
is a valid underlying type, it is not one of the keywords which the C# grammar permits to appear in that location.
Quoting the grammar:
enum-declaration:
attributesoptenum-modifiersopt
enum
identifier enum-baseoptenum-body;
optenum-base:
:
integral-typeintegral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With