views:

115

answers:

3

I know that you can't use inheritance with enums, so in my base class I want to define that the classes that implement it must return an enum of some type for a property.

Ideally, this would be like:

public abstract BaseEnum MyEnum { get; set; }

Then all the implementers would have to return some form of enum. But obviously BaseEnum doesn't exist. I can use object, but I'd rather not.

Is there a nice way of doing this?

Edit: I'm asking this because I essentially want to keep the name of the property in the implementing classes the same - I know that I won't be able to work with the enum in the base class, but if I didn't put it in the base, then the implementing classes could decide on their own property names for their enum, which could become unclear over time, as they would drift towards their own implementations.

+3  A: 

All Enums inherit from System.Enum.

Robert Giesecke
+1  A: 

You should take a look here: Enum “Inheritance”:

See section 8.5.2 of the CLI spec for the full details.
Relevant information from the spec

 * All enums must derive from System.Enum
 * Because of the above, all enums are value types and hence sealed
Rubens Farias
+2  A: 

The closest you can easily come in C# is to make the type generic with a struct constraint:

public abstract class BaseClass<T> where T : struct
{
    public abstract T MyEnum { get; set; }
}

then

public class DerivedClass : BaseClass<SomeEnum>

C# won't let you specify a constraint restricting you to enum types, even though the CLI does support it. I have a project called Unconstrained Melody which uses post-build tricks to enforce such a constraint - but I wouldn't suggest you take the same approach unless you're feeling somewhat daring. The struct constraint will at least limit you to value types, which may be good enough.

Jon Skeet
Oooh I like it, I knew I had overlooked something.However, just to complicate things, I then have another class that uses a list of these base classes, so:public List<BaseClass<Enum>> MyObjects { get; set; }which then doesn't compile as the T has to be a value type. What can I put in its place to make this work?
Fiona Holder
Does that have to be able to hold different kinds of BaseClass (i.e. for different enums), or just several instances of the same kind? You may need to have a nongeneric base class for the base class, which then wouldn't contain that property.
Jon Skeet
Different kinds of BaseClass. I've now got a nongeneric base for the base class and it's working fine, thanks.
Fiona Holder