<matty.hall@gmail.com> wrote:[color=blue]
> I have two classes: a base class (BaseClass) and a class deriving from
> it (DerivedClass). I have a List<DerivedClass> that for various
> reasons needs to be of that type, and not a List<BaseClass>. However, I
> need to cast that list to a List<BaseClass> and it is not working. The
> code is below. I get the following exception:
>
> "Unable to cast object of type 'System.Collections.Generic.List`1' to
> type 'System.Collections.Generic.List`1'."
>
> Replacing the line "baseClasses = (List<BaseClass>) temp;" with
> "baseClasses = (List<BaseClass>) derivedClasses" causes the compiler to
> show an error:
>
> "Cannot convert type
> 'System.Collections.Generic.List<ConsoleApplicatio n1.DerivedClass>' to
> 'System.Collections.Generic.List<ConsoleApplicatio n1.BaseClass>'"
>
> Is there anyway to accomplish this? Code follows...[/color]
No. List<DerivedClass> isn't derived from List<BaseClass>. If it were,
you'd be able to do:
List<String> x = new List<String>();
List<Object> y = x;
y.Add (new Object()); // Bang! x is only meant to contain strings...
--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too