generics and inheritance: List<T>

J

jonpb

Hi,

The following code:

public class SubPoint2D : Point2D
{
public int Code;
}

void ProcessPoints(List<Point2D> pts)
{
return;
}

private void Test()
{
List<SubPoint2D> subPts2D = new List<SubPoint2D>();

ProcessPoints(subPts2D);
}

results in a compiler error: cannot convert List<SubPoint2D> to
List<Point2D>.

Is there a way to tell the compiler that SubPoint2D actually is a
Point2D and therefore the two List<T> types are equivalent as far as
Point2D? I tried:
ProcessPoints(subPts2D as List<Point2D>);
but that didn't work either.

Thanks,
John
 
J

Jon Skeet [C# MVP]

jonpb said:
The following code:

public class SubPoint2D : Point2D
{
public int Code;
}

void ProcessPoints(List<Point2D> pts)
{
return;
}

private void Test()
{
List<SubPoint2D> subPts2D = new List<SubPoint2D>();

ProcessPoints(subPts2D);
}

results in a compiler error: cannot convert List<SubPoint2D> to
List<Point2D>.

Is there a way to tell the compiler that SubPoint2D actually is a
Point2D and therefore the two List<T> types are equivalent as far as
Point2D?

They're not equivalent at all.

Consider what happens when you try to add a Point2D to each of them:
with a List<Point2D> it's fine. With a List<SubPoint2D> it should go
bang.

Basically generics in C# don't support covariance. It's a pain, but it
also gives more safety. It's likely that C# 4 will have more support
for this, at the interface and delegate level, but that's all.

What you *can* do is make ProcessPoints a generic method:

void ProcessPoints(List<T> pts) where T : Point2D

That may help you, depending on what you need to do in ProcessPoints.
 
J

jonpb

Jon said:
They're not equivalent at all.

Consider what happens when you try to add a Point2D to each of them:
with a List<Point2D> it's fine. With a List<SubPoint2D> it should go
bang.

Basically generics in C# don't support covariance. It's a pain, but it
also gives more safety. It's likely that C# 4 will have more support
for this, at the interface and delegate level, but that's all.

What you *can* do is make ProcessPoints a generic method:

void ProcessPoints(List<T> pts) where T : Point2D

That may help you, depending on what you need to do in ProcessPoints.

Thanks very much Jon. The generic method works in this particular case,
as all it does is draw the shape there is no manipulation of the lists
or changing of values, but your point is well taken.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

slowness part2 2
Problem with overloaded functions 4
Generic puzzle 4
Polymorphic generics 4
Generics 2
a question about binary serialization 3
Inheritance Question 4
Is it based up polymorphy or just inheritance? 2

Top