Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you use just the alias to declare a enum and not the .NET type?

Tags:

c#

.net

types

enums

This works perfectly..

public  enum NodeType : byte
{ Search, Analysis, Output, Input, Audio, Movement} 

This returns a compiler error...

public  enum NodeType : Byte
{ Search, Analysis, Output, Input, Audio, Movement} 

Same happen when using reflection...

So, does somebody know why the enum-base is just an integral-type?

like image 975
MrVoid Avatar asked Nov 11 '14 14:11

MrVoid


People also ask

Can enum be declared inside a method C#?

Question 6: An enum cannot be declared inside a method. Enums can only be declared inside class or namespace. Learn enum in detail. Learn C# enums.

What is enum in .NET core?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members: C# Copy.

Is enum primitive type C#?

What is Enum in C#? C# enum is a value type with a set of related named constants often referred as an enumerator list. The C# enum keyword is used to declare an enumeration. It is a primitive data type, which is user-defined.

Can an enum be null C#?

Enum types cannot be nullable.


2 Answers

Probably it is just a incomplete compiler implementation (while documented).

Technically, this should work too, but it doesn't.

using x = System.Byte;

public  enum NodeType : x
{ Search, Analysis, Output, Input, Audio, Movement}

So the parser part of the compiler just allows the fixed list byte, sbyte, short, ushort, int, uint, long, or ulong. There is no technical restriction I am aware of.

like image 109
Patrick Hofman Avatar answered Oct 06 '22 00:10

Patrick Hofman


Because the specs say so:

enum-declaration:
attributesopt enum-modifiersopt enum identifier enum-baseopt enum-body ;opt

enum-base:
: integral-type

enum-body:
{ enum-member-declarationsopt }
{ enum-member-declarations , }

Each enum type has a corresponding integral type called the underlying type of the enum type. This underlying type must be able to represent all the enumerator values defined in the enumeration. An enum declaration may explicitly declare an underlying type of byte, sbyte, short, ushort, int, uint, long or ulong. Note that char cannot be used as an underlying type. An enum declaration that does not explicitly declare an underlying type has an underlying type of int.

...

integral-type is defined as,

integral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char

like image 35
Selman Genç Avatar answered Oct 05 '22 23:10

Selman Genç