Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can Enum contains other Enum?

Can Enum contains other Enum elements plus its own elements ?

public enum CardSuit
{
    spades,
    hearts,
    diamonds,
    clubs 
}

public enum GameSuit
{
    spades,        //        These are 
    hearts,        //        the same
    diamonds,      //      " CardSuit "
    clubs,         //        elements

    suns    //             " GameSuit " special element
}

Can we include CardSuit in GameSuit without redundant retyping same elements ?

like image 209
Ahmed Ghoneim Avatar asked Jun 10 '12 01:06

Ahmed Ghoneim


People also ask

Can enum include another enum?

You can even include another enum!

Can enums inherit from other enums?

Enums cannot inherit from other enums. In fact all enums must actually inherit from System. Enum . C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.

Can you have 2 enums the same value?

CA1069: Enums should not have duplicate values.

Can I have enum inside enum in Java?

Core Java bootcamp program with Hands on practiceYes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.


2 Answers

Sadly no, there's no good solution for what you want using enums. There are other options you can try, such as a series of public static readonly fields of a particular "enum-like" type:

public class CardSuit 
{
    public static readonly CardSuit Spades = new CardSuit();
    public static readonly CardSuit Hearts = new CardSuit();
    ...
}

public enum GameSuit : CardSuit 
{
    public static readonly GameSuit Suns = new GameSuit();
}

In practice, this can work mostly as well, albeit without switch statement support. Usage might be like:

var cardSuit = ...;
if (cardSuit == CardSuit.Spades || cardSuit == GameSuit.Suns) { ... }
like image 122
Kirk Woll Avatar answered Oct 14 '22 19:10

Kirk Woll


What you have typed is legal but both enums are independent of each other.

GameSuit enum spades has no connection with CardsSuit enum spades.

like image 37
Nikhil Agrawal Avatar answered Oct 14 '22 21:10

Nikhil Agrawal