Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

why use base?

why does he have to use :base(x , y) and he already created a constructor

1 Answer

Shadab Khan
Shadab Khan
5,470 Points

Hi Hamza, To start with, I'd advise you to rewatch the video on inheritance topic carefully as the :base keyword is related to the concept of inheritance in C#.

for e.g. imagine a parent class 'Vehicle' and a child class 'Car' inheriting from parent class 'Vehicle'.

Basically, based on the inheritance relationship in Object Oriented Programming, a Car is a Vehicle; which essentially means, that when you're creating a Car object in your program using constructor (see below e.g.) you're also creating a Vehicle for which you require to initialize the values. After inheriting the Vehicle class in Car class you simply can't create a Car object with DealerShip information, can you? You need to provide other details of Car e.g. ModelNo, DateOfManufacture etc. which can be found in the Vehicle class to completely build your car object, which is precisely you use the 'base' keyword for. It is used to initialize the parent class's members via parameterized constructor whenever a child class object is created.

class Vehicle
{
  public string ModelNo {get; set;}
  public DateTime DateOfManufacture {get; set;}
  public int MaxSpeed {get; set;}

  public Vehicle(string modelNo, DateTime dateOfManufacture, int maxSpeed)
  {
         ModelNo = modelNo;
         dateOfManufacture = dateOfManufacture;
         MaxSpeed = maxSpeed;
  }
}

class Car : Vehicle
{
   public string DealerShip {get; set;}

   public Car(string dealership, string modelNo, DateTime dateOfManufacture, int maxSpeed) 
                                        : base(modelNo, dateOfManufacture, maxSpeed)
   {
      DealerShip = dealership;
   }
}

I hope that helps, happy coding!