Hi,
I'm hoping someone could help solve this problem I've run into. I'm
trying to cast a GenericCollection<Car> to a derived class which
is essentially the same thing. The compiler seems happy, but I get a runtime error saying
that its not possible, but it doesn't make sense. Surely CarCollection
would have all the methods/properties/structures that its parent has
I've cut down the code to make it as basic as possible. To run it, just
instantiate a new Foo.testInheritance();
The ultimate goal
is I want to add a Clone() method to the GenericCollection and reuse it
in the inherited class. How can I go about doing this
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace Foo
{
public class GenericCollection<T> : BindingList<T>
{
}
public class CarCollection : GenericCollection<Car>
{
}
public class Car
{
}
class testInheritance
{
public testInheritance()
{
GenericCollection<Car> gcar = new GenericCollection<Car>();
// error "Unable to cast object
of type Foo.GenericCollection`1' to type 'Foo.CarCollection'.
CarCollection cc =
(CarCollection)gcar;
}
}
}

Cast generic to derived type
Andrew Raymond
Well, you can't cast something to a derived class. That's like writing:
object o = new object();
string s = (String) o;
Even though in your case, the two types are a bit more alike :)
Anyway, I can imagine you want to write a Clone() method for all subclasses of GenericCollection. This is a bit more involved though than just casting it, but can work like this:
public class GenericCollection<T,TList> : BindingList<T>
where TList : GenericCollection<T,TList>,new() {
public TList Clone() {
TList result = new TList();
// <copy items>
return result;
}
}
public class CarCollection : GenericCollection<Car, CarCollection> {}
Ramakrishna Neela
Cheers :)
office of technology
public testInheritance()
{
GenericCollection<Car> gcar = new CarCollection();
// error "Unable to cast object of type Foo.GenericCollection`1' to type 'Foo.CarCollection'.
CarCollection cc = (CarCollection)gcar;
}
You can cast an object reference to a derived type if and only if the object actually IS of that type (the reference can be of that type or any parent class of that type).