Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I base an enum off UInt16?

Tags:

c#

.net

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?

like image 408
ojlovecd Avatar asked Oct 28 '11 03:10

ojlovecd


1 Answers

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-modifiersoptenum identifier enum-baseoptenum-body ;opt

enum-base:

: integral-type

integral-type:

sbyte

byte

short

ushort

int

uint

long

ulong

char

like image 100
Ben Voigt Avatar answered Sep 30 '22 18:09

Ben Voigt