Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does enum declaration accept short but not Int16

Tags:

c#

.net

enums

I want to declare a new enum with non-default underlying type. This works:

public enum MyEnum : short
{ A, B, C, }

But I don't understand the reason why this doesn't compile:

public enum MyEnum : System.Int16
{ A, B, C, }

Compiler says

Type byte, sbyte, short, ushort, int, uint, long, or ulong expected

I understand that short is an alias for Int16 on all .NET versions (32/64 bit flavors included). I don't see why the compiler gives a different meaning to the alias in that particular case.

Any explanation?

like image 844
Johann Blais Avatar asked Jun 01 '11 09:06

Johann Blais


People also ask

Is Int16 same as short?

Next The program's output shows that Int16 is equal to short, Int32 is equal to int, and Int64 is equal to long in the runtime.

How do you specify the size of an enum?

The C standard specifies that enums are integers, but it does not specify the size. Once again, that is up to the people who write the compiler. On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less.


2 Answers

The syntax is correct. C# specification explicitly states that the enum's underlying type must be byte, sbyte, short, ushort, int, uint, long or ulong.

Read what Microsoft says about this here.

like image 169
Daniel Daranas Avatar answered Oct 17 '22 02:10

Daniel Daranas


"...The second example is trying to inherit from a type that derives from System.ValueType, which is strictly prohibited..."

Read here:

like image 40
danyolgiax Avatar answered Oct 17 '22 04:10

danyolgiax