tags:

views:

225

answers:

3

I have a base class which needs to define an enumeration:

BaseClass - SomeEnum

I then need to create two derived classes from the base class and extend the values in the enumeration:

ChildClass1 : BaseClass - SomeEnum - SomeEnumValue1

ChildClass2 : BaseClass - SomeEnum - SomeEnumValue2

In C# or VB.NET can someone provide the syntax to do this? Or if not possible suggest an alternative to what I'm trying to do? Thanks!

+7  A: 

Extending the list of values in an enumeration is not possible. Enumerations are static at their point of declaration and compilation.

Your alternative is to stop using enumerations and replace it with some other datatype or class hierarchy.

dkackman
I would also suggest investigating the possibility of using aggregation instead of inheriting from a base class.
Padu Merloti
A: 

Hey,

The best option would be to do:

public class ChildClass1
{
  new public NewEnumValueList SomeEnum
  {
    ..
  }
}

Where this new property returns a completely new list of enum values, or as mentioned elsewhere, use the state pattern.

Brian
A: 

Others have indicated that this is not possible. I'll defer to them on the specifics of the language. This answer is more "what to do since it doesn't work."

Obviously, your options depend on your application. I've seen enums most often to give a name and naming scope to an otherwise arbitrary integer value (as opposed to using macros). If this is your usage, you could take the alternative of building a dictionary (or pair of dictionaries) to maintain indexes to these names and values. In your base class, you'd populate it with the default values. In child classes, you add to it the same way. In grandchild classes, you add to it the same way. in great-grandchild classes, you add....

The overhead of such a system should be minimal, since you are just hashing relatively short strings as names, in addition to store integers. You do take a hit at run-time compared to using a compiled-in comparison of int values, but the lookup should be negligible unless you are on a real-time (unlikely if C# is your language) system or an enterprise system.

San Jacinto