If you've ever tried to cast been list generics, you know that you can't.
1. You have two classes Shape and Square, where Square inherits from Shape.
2. You have two generic lists, List<Shape> and List<Square>.
3. List<Square> does not inherit from List<Shape>. So you cannot cast List<Square> to a List<Shape>. It seems intuitive that it should be possible, but it isn't.
You can find more information here, in the "Constructed Types" section, subsection "Conversions", of the C# Version 2.0 Specification Document. The important part is as follows:
"No special conversions exist between
constructed reference types other than those described in §6. In particular,
unlike array types, constructed reference types do not exhibit “covariant”
conversions. This means that a type List<B> has no
conversion (either implicit or explicit) to List<A> even if
B is derived from A. Likewise, no conversion exists from
List<B> to List<object>."
"The rationale for this is simple: if a
conversion to List<A> is permitted,
then apparently one can store values of type A into the list. But this
would break the invariant that every object in a list of type List<B> is always a value of type B, or else unexpected failures
may occur when assigning into collection classes."
Since you cannot cast between them, you end up having to create a new list, code a for loop, and add the items from one list to the other list. Not a big deal, but i got tired of writing the for loop. :) So here is the utility method i created to do it for me:
Here is a test i wrote for my method:
Ok, Ok, I know its basically just a for loop. But I think the use of a generic method is kind of cool, and it makes my code read a lot better when i have to "cast" a whole bunch of List<>'s. If anyone knows of a better way, please let me know!
06-13-2007 1:50 PM