Is it possible to combine multiple enums together? Below is code sample of what I would like to see:
enum PrimaryColors
{
Red,
Yellow,
Blue
}
enum SecondaryColors
{
Orange,
Green,
Purple
}
//Combine them into a new enum somehow to result in:
enum AllColors
{
Red,
Orange,
Yellow,
Green,
Blue,
Purple
}
It does not matter what order they are, or what their backing numbers are, I just want to be able to combine them.
For context, this is so that multiple classes for a program I am working on would have enums associated with what they do. My main program would read all of the enums available from each of the support classes and make a master list of available enums of available commands (the the enums are for).
Edit: The reason for these enums is because my main program is reading in a list of commands to perform at certain times, and so I want to read in the file, see if the command in it is associated with one of my enums, and if it is, put it into a list of commands to perform.
You can use the '|' (bitwise OR ) operator to mask multiple roles together in a single 64-bit integer, which you can store in the database in an integer field (a bigint ). RoleEnum userRoles = RoleEnum.
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.
Inheritance Is Not Allowed for Enums.
Not sure I understand precisely. But you can make a List<>
of all the values like this:
var allColors = new List<Enum>();
allColors.AddRange(Enum.GetValues(typeof(PrimaryColors)).Cast<Enum>());
allColors.AddRange(Enum.GetValues(typeof(SecondaryColors)).Cast<Enum>());
Instead of List<Enum>
you could also use HashSet<Enum>
. In any case, because you assign a PrimaryColor
or SecondaryColor
to a class type (namely System.Enum
), you get boxing, but that's just a technical detail (probably).
The reason for these enums is because my main program is reading in a list of commands to perform at certain times, and so I want to read in the file, see if the command in it is associated with one of my enums, and if it is, put it into a list of commands to perform.
This seems like you don't want three different enum
types, you want one type (what you call “master enum
”) plus some way to decide which of the sub-enums a certain value belongs to. To do that, you can use a collection of values from your master enum, or a switch
.
For example:
enum Color
{
Red,
Orange,
Yellow,
Green,
Blue,
Purple
}
bool IsPrimaryColor(Color color)
{
switch (color)
{
case Color.Red:
case Color.Yellow:
case Color.Blue:
return true;
default:
return false;
}
}
Also, you should use a singular name for enum
types (unless it's a flag enum
).
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