Results 1 to 3 of 3

Thread: Inheritance and Collections

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jan 2005
    Location
    Christchurch, NZ
    Posts
    18

    Question 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

  2. #2
    Frenzied Member DeadEyes's Avatar
    Join Date
    Jul 2002
    Posts
    1,196

    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.

  3. #3
    PowerPoster hellswraith's Avatar
    Join Date
    Jul 2002
    Location
    Washington St.
    Posts
    2,464

    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
  •  



Click Here to Expand Forum to Full Width