2

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!

M_bay
  • 201
  • 1
  • 2
  • 5

3 Answers3

2

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

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

Community
  • 1
  • 1
saunderl
  • 1,618
  • 2
  • 16
  • 31
  • 1
    +1 for a good reference, but that one is C# specific and OP hasn't specified a language. It also doesn't have an accepted answer yet. OP, which language are you targetting? – Mawg says reinstate Monica Jul 15 '10 at 02:36
2

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.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
1

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.

Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551