cast List<SubClass> to ICollection<Class>




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?





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.


Thanks, Pete!

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

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