Search code examples
c#silverlightenumsienumerable

can Enum contains other Enum?


Can Enum contains other Enum elements along with 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 ?


Solution

  • 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) { ... }