I have a compiler error when trying to set a generic base collection class member in this derived class.
error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<IntSegment>' to 'System.Collections.Generic.List<T>'
Here’s the outline of my generic collection
public class Path<T> : IEnumerable<T> where T : Segment
{
private List<T> segments = new List<T>();
public List<T> Segments
{
set { segments = value; }
get { return this.segments; }
}
public Path()
{
this.Segments = new List<T>();
}
public Path(List<T> s)
{
this.Segments = s;
}
}
A derived generic class of this collection is then defined for a derived class IntSegment of Segment (for which the base collection is defined)
public class IntersectionClosedPath<T> : Path<T>, IEnumerable<T> where T : IntSegment
{
public IntersectionClosedPath(List<IntSegment> inEdges)
: base()
{
Segments = inEdges;
}
}
I can’t understand why this assignment is not allowed. (I don’t need to make a deep copy of the incoming List).
Change
List<IntSegment> inEdgestoList<T> inEdgesand it will work. The problem is thatSegmentsis known as aList<T>,where T : IntSegment, whileinEdgesis aList<IntSegment>. (For reasons I’ll not go into here unless you ask, such an assignment is not allowed. Look up variance/covariance/contravariance if you’re interested.)