23

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?

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
Johann Blais
  • 9,389
  • 6
  • 45
  • 65
  • I remember a similar question getting closed yesterday – V4Vendetta Jun 01 '11 at 09:57
  • I found two almost identical questions using Google: http://stackoverflow.com/questions/3774650/enum-members-of-int32-type and http://stackoverflow.com/questions/1813408/c-int-int32-and-enums. – Daniel Daranas Jun 01 '11 at 10:00
  • I didn't find it despite several minutes spent on reading search results :) – Johann Blais Jun 01 '11 at 10:00
  • @Daniel Daranas, sorry I searched using int16 as a keyword... it might explain why I didn't find them – Johann Blais Jun 01 '11 at 10:02
  • @Johann Blais, my search was this: http://www.google.com/search?q=c%23+enum+type+declaration+int16&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:ca:official&client=firefox-a#sclient=psy&hl=en&client=firefox-a&hs=dl3&rls=org.mozilla:ca%3Aofficial&source=hp&q=c%23+enum+type+declaration+int16+site:stackoverflow.com&aq=f&aqi=&aql=&oq=&pbx=1&fp=1&biw=784&bih=532&bav=on.2,or.r_gc.r_pw.&cad=b – Daniel Daranas Jun 01 '11 at 10:08
  • @Daniel Daranas: unfortunately, this search now leads first to this question ;) – Johann Blais Jun 01 '11 at 11:25

2 Answers2

21

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.

Lars Gyrup Brink Nielsen
  • 3,939
  • 2
  • 34
  • 35
Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
4

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

Read here:

Anil
  • 387
  • 2
  • 24
danyolgiax
  • 12,798
  • 10
  • 65
  • 116