Generics and inheritance

G

Guest

Why isn't List<A> a subclass of List<B> if A is a subclass of B ?

This fact causes a lot of design problems. Making the generic collections
loose their type safty strength in large designs.
Maybe there is a design pattern to overcome this problem ? Or maybe someone
knows other related facts ?
 
J

Jon Skeet [C# MVP]

uriye said:
Why isn't List<A> a subclass of List<B> if A is a subclass of B ?

This fact causes a lot of design problems. Making the generic collections
loose their type safty strength in large designs.
Maybe there is a design pattern to overcome this problem ? Or maybe someone
knows other related facts ?

Suppose you have List<FileStream> and try to use it as a List<Stream> -
you would be able to add a List<NetworkStream> to it, which wouldn't be
good. (This is how arrays work, with runtime exceptions, and I'm not at
all sure it's ideal.)

So in fact, currently we *do* have type safe collections - but with
your suggestion, they wouldn't be type safe any more.
 
R

Robert Jordan

Hi Jon,
Suppose you have List<FileStream> and try to use it as a List<Stream> -
you would be able to add a List<NetworkStream> to it, which wouldn't be
good. (This is how arrays work, with runtime exceptions, and I'm not at
all sure it's ideal.)

So in fact, currently we *do* have type safe collections - but with
your suggestion, they wouldn't be type safe any more.

Hmm, I don't get that explanation. Supposing I have a method

void LoadFrom(Stream stm)

That method can be type-safely called with a XyzStream, as long
the XyzStream is a subclass of Stream.

Now extrapolated:

void LoadFrom(List<Stream> list)

I'd naively expect to be able to pass a List<XyzStream> object
to that method, too.

bye
Rob
 
J

Jon Skeet [C# MVP]

Robert Jordan said:
Hmm, I don't get that explanation. Supposing I have a method

void LoadFrom(Stream stm)

That method can be type-safely called with a XyzStream, as long
the XyzStream is a subclass of Stream.

Indeed - because any change to the value of stm is only visible within
the method. Note that if it were a pass-by-reference parameter, you
couldn't, for precisely the reason given below.
Now extrapolated:

void LoadFrom(List<Stream> list)

I'd naively expect to be able to pass a List<XyzStream> object
to that method, too.

And what would you expect to happen if LoadFrom contained:

list.Add (new MemoryStream());

?
 

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

Top