Inheritance and Collections
I have a base class called Vehicle and a collection of Vehicles called VehicleCollection.
I created another class called Truck derived from the base class Vehicle. The Truck class has an extra property called Trailer.
Can I create an instance of the VehicleCollection and add a Truck object to the collection?
If so how can I access the property Trailer? myVehicle[0].Trailer doesn't work.
Any advice on how to get round this would be great.
Thanks
R
Re: Inheritance and Collections
If your collection stores items as type object you can
Truck t = (Truck)myVehicle[0];
and checking that it is of type Truck.
Given that this looks more like a learning example the solution probably lies in creating an Interface IVehicle.
Re: Inheritance and Collections
Doing this is a more safe way to do it so you don't accidently get a Car trying to be cast into a Truck:
Code:
Truck t = myVehicle[0] as Truck;
if(t != null)
{
t.Trailer = new Trailer();
}