M_bay
M_bay

Reputation: 211

How to import another Enum into My Enum

This is my Enum

public enum MyEnum {Blue, Red};

There is another external enum called ExternalEnum, I don't have and couldn't change its source code but I can use the class, say I know there are yellow and white in it.

What I want to do is to pull all the elements in the external enum, make them part of my enum, i.e.

public enum MyEnum {Blue, Red, ExternalEnum.Yellow, ExternalEnum.White};

Is there a way I can do this easily so each time I get a new version of ExternalEnum I don't need to manually go over all its elements? I don't want to use extend (subclass) as they belong to different package.

Thanks!

Upvotes: 2

Views: 509

Answers (3)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112642

You can do it by redefining the enum constants like this:

public enum ExternalEnum
{
    White, // -> 0
    Black  // -> 1
}

public enum MyEnum
{
    White = ExternalEnum.White, // -> 0
    Black = ExternalEnum.Black, // -> 1
    Red, // -> 2
    Blue // -> 3
}

However, you must ensure that the integer values of the enum constants do not overlap. The easiest way of doing it, is to declare the external constants first. There is no such thing like an automatic import into enums. You cannot extend enums.

Upvotes: 2

Mawg
Mawg

Reputation: 40185

Since you don't specify a lnguage it is very difficult to help you, but I suspect that what you want to do might be easier in interpreted languages than compiled.

Upvotes: 1

saunderl
saunderl

Reputation: 1638

What you are talking about is a "Dynamic Enum".

Here is a link to a previous question here at StackOverflow.

Upvotes: 2

Related Questions