Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum inheriting from int

I've found this all over the place in this code:

public enum Blah: int {     blah = 0,     blahblah = 1 } 

Why would it need to inherit from int? Does it ever need to?

like image 896
slandau Avatar asked Jun 14 '11 19:06

slandau


People also ask

Can enum be inherited?

Enums cannot inherit from other enums. In fact all enums must actually inherit from System.

Is it possible to inherit enum in C#?

Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.

Can enum inherit from another enum Java?

You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.

Is enum a class C#?

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).


2 Answers

According to the documentation:

Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int.

So, no, you don't need to use int. It would work with any integral type. If you don't specify any it would use int as default and it's this type that will be used to store the enumeration into memory.

like image 83
Darin Dimitrov Avatar answered Oct 04 '22 10:10

Darin Dimitrov


Enums are implicitly backed by integers.
: int just restates the default, just like void M(); vs. private void M();.

You can also create enums that are backed by other intergral types, such as enum GiantEnum : long.

like image 44
SLaks Avatar answered Oct 04 '22 10:10

SLaks