beta2 - generics & casting on collections

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can I make the following code work on beta 2?
(I'm not sure but I think it worked on the beta1 version of VS2005)

Public Person: IPerson
{
....
}

....
List<IPerson> persons = (List<IPerson>)new List<Person>();
//Error: Cannot convert type...
 
because List<IPerson> and List<Person> are completely different types and
therefore not compatible.
 
But if Person inherits from IPerson then a list of Person should also be a
list of IPerson.
Does this mean that it is not possible to cast any type of collection to any
other if the generic parameters are of diferent kinds, even if there's an
inheritance relationship involved in the parameters?
That would mean I always had to declare the collections of the upper type in
the inheritance hierarchy.
 
But if Person inherits from IPerson then a list of Person should also be a
list of IPerson.

No, because with a List<IPerson> you can insert anything implementing
IPerson, even if it isn't a Person. That would violate the
List<Person> contract.

Arrays behave the way you describe (Person[] can be assigned to
IPerson[]) which can cause runtime type violation exceptions.

That would mean I always had to declare the collections of the upper type in
the inheritance hierarchy.

Yes. Is that a problem?



Mattias
 
But if Person inherits from IPerson then a list of Person should also be a
No, because with a List<IPerson> you can insert anything implementing
IPerson, even if it isn't a Person. That would violate the
List<Person> contract.

Thanks for your help. I understand what you're saying, however I don't see
any reason besides technical constraints for that not being possible. In the
case where you would insert another IPerson type object that didn't
implement Person, a runtime exception would be generated, like in the Array
case you mentioned.
For me this kind of behaviour would be prefered than not allowing for the
cast to be performed.
 
The problem is that List<Person> does not inherit from List<IPerson>. These
both are completely different types, they even wouldn't share static fields
if their base class would have any.
 
Back
Top