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 ?
You can even include another enum!
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.
CA1069: Enums should not have duplicate values.
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.
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) { ... }
What you have typed is legal but both enums are independent of each other.
GameSuit
enum spades has no connection with CardsSuit
enum spades.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With