How to correct this design. Error because C# doesn’t allow Type Covariance.
How can I improve or correct this design
public interface ITimeEvent
{
}
public interface IJobTimeEvent : ITimeEvent
{
}
public interface IActivityTimeEvent : ITimeEvent
{
}
public interface IAssignmentTimeEvent<T> where T : ITimeEvent
{
T ParentTimeEvent
{
get;
set;
}
}
public class ScheduleJobTimeEvent : IAssignmentTimeEvent<IJobTimeEvent>
{
public IJobTimeEvent ParentTimeEvent
{
get;
set;
}
}
public class ScheduleActivityTimeEvent : IAssignmentTimeEvent<IActivityTimeEvent>
{
public IActivityTimeEvent ParentTimeEvent
{
get;
set;
}
}
List<IAssignmentTimeEvent<ITimeEvent>> lst = new List<IAssignmentTimeEvent<ITimeEvent>>();
lst.Add(new ScheduleJobTimeEvent()); //Error because C# doesn't allow Type Covariance
lst.Add(new ScheduleActivityTimeEvent()); //Error because C# doesn't allow Type Covariance
You can make this work in C# 4.0, although you need to add the covariance specifier to the interface type parameter.
However, for this to work at all, you must guarantee that the type parameter will only be used in method call results (and not parameters), which means surrendering your interface property setter. Whether or not this is acceptable for the overall design is your call.