|
-
May 5th, 2005, 12:47 AM
#1
Thread Starter
Junior Member
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
-
May 5th, 2005, 03:07 AM
#2
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.
-
May 14th, 2005, 04:19 PM
#3
PowerPoster
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();
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|