Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about inheritance and OOP c#

Tags:

c#

oop

I have a persistent object which for the sake of this question, I'll car CAR class.

public class Car
{
   public string model {get;set}
   public int year {get;set}
}

Obviously hugely simplified.

Now, as the code developed I naturally created a function which accepts CAR as a parameter. For example:

public void PaintCar (Car theCar)
{
  //Does some work
}

So far so good, but then I had a scenario where I needed another class, which was very similar to CAR, but car was missing some fields. No problem I thought OOP to the rescue, I'll just inherit from Car, to end up with:

public class SuperCar : Car
{
   public string newProp {get;set}
   // and some more properties
}

Once again everything looked peachy, until I came across a very useful utility function I was using to populate Cars original properties.

Public void SetCarProperties(Car theCar)
{
    //sets the properties for car here
}

I thought mmm, I wish I could use that same function to set the properties for my superCar class without needing an override. I also don't want to change the base car definition to include all properties of the superCar class.

At this point I hit a dilemma. The override would work, but it is extra work. Is there a more elegant solution. Basically I want to pass through the superclass to a function that is expecting a base class. Is this possible with c#?

My final code result would be something like :

Car myCar = new Car(); 
SetCarProperties(myCar); // ALL GOOD

SuperCar mySuperCar = new SuperCar(); 
SetCarProperties(mySuperCar); // at the moment this function is expecting type Car...
like image 585
JL. Avatar asked Dec 10 '22 06:12

JL.


1 Answers

A more elegant solution is to put the function SetCarProperties on the Car class and override it in SuperCar to use base to fill Car's properties and some additional code to fill SuperCar properties.

Edit: otherwise known as polymorphism.

like image 156
Paweł Obrok Avatar answered Dec 22 '22 00:12

Paweł Obrok