cast List<SubClass> to ICollection<Class>

  • Thread starter Thread starter Ryan
  • Start date Start date
R

Ryan

Hi,

How can I get around runtime error that says I can not explicit cast
List<SubClass> to ICollection<Class>?

Generic List inhertis generic ICollection and
Subclass inherits Class,

then should not a problem to cast it explicitly, right?

Thanks!
 
Peter Duniho said:
It is and should be a problem to cast it. If you could cast it, then you
could then treat your List<SubClass> collection as if it was the
more-general ICollection<Class>. And if you can do that, then you can add
an instance of Class to your object that is really a List<SubClass>. And
if you can do that, then all of the sudden you have no way to guarantee
that everything in your List<SubClass> is really an instance of SubClass.

Google (the web or this newsgroup) for the keywords "covariant",
"covariance", and "generic". This is a fairly common question and there
is a lot more in-depth discussion in this newsgroup and elsewhere.

As an interesting side-note: C# 4.0 is supposed to include support for
covariant generics. It still won't apply in this case -- they aren't
allowing covariance anywhere that doing so could break something -- but it
will address this very common question in other scenarios where it
actually _is_ safe to cast something in this way.

Pete

Thanks, Pete!

Seems we need a read only collection and allow safe cast.
 
Back
Top