Enums and inheritance

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-04-06T23:40:28Z Indexed on 2010/04/06 23:43 UTC
Read the original article Hit count: 126

I will use (again) the following class hierarchy:

Event

and all the following classes inherit from Event:

SportEventType1 SportEventType2 SportEventType3 SportEventType4

I have originally designed the Event class like this:

public abstract class Event
{
    public abstract EventType EventType { get; }
    public DateTime Time { get; protected set; }

    protected Event(DateTime time) {
        Time = time;
    }
}

with EventType being defined as:

public enum EventType {
    Sport1,
    Sport2,
    Sport3,
    Sport4
}

The original idea would be that each SportEventTypeX class would set its correct EventType. Now that I think of it, I think this approach is totally incorrect for two reasons:

  1. If I want to later add a new SportEventType class I will have to modify the enum
  2. If I later decide to remove one SportEventType that I feel I won't use I'm also in big trouble with the enum.
  3. I have a class variable in the Event class that makes, afterall, assumptions about the kind of classes that will inherit from it, which kinda defeats the purpose of inheritance.

How would you solve this kind of situation? Define in the Event class an abstract "Description" property, having each child class implement it? Having an Attribute(Annotation in Java!) set its Description variable instead? What would be the pros/cons of having a class variable instead of attribute/annotation in this case? Is there any other more elegant solution out there?

Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about java