Question on inheritance and OOP C #

I have a permanent object, which I will use the CAR class for this question.

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

Obviously very simplified.

Now that the code is developed, I naturally created a function that takes CAR as a parameter. For instance:

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

So far, so good, but then I had a scenario where I needed a different class that was very similar to CAR, but some fields were missing on the machine. No problem, I thought OOP to the rescue, I’ll just inherit from Car, so that in the end:

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

Again, everything looked peachy until I came across a very useful useful function that I used to populate the original properties of Cars.

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

I thought that mmm, I would like to use the same function to set properties for my superCar class without the need for overriding. I also do not want to change the definition of the base machine to include all the properties of the superCar class.

At this moment, I was faced with a dilemma. Replacing will work, but this is additional work. Is there a more elegant solution. Basically, I want to pass a superclass to a function that expects a base class. Is this possible with C #?

My final code result would look something like this:

 Car myCar = new Car(); SetCarProperties(myCar); // ALL GOOD SuperCar mySuperCar = new SuperCar(); SetCarProperties(mySuperCar); // at the moment this function is expecting type Car... 
+4
source share
3 answers

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

Edit: otherwise known as polymorphism.

+12
source

Introduce an override, but an initial call to the base class version to configure common properties:

 public void SetCarProperties(Car car) { // set general properties } public void SetCarProperties(SuperCar veyron) { this.SetCarProperties((Car) veyron); // SuperCar specific properties } 
+2
source

SuperCar sCar = car like SuperCar; if (sCar! = null) {set properties to a scar; }

set properties on a car;

-1
source

All Articles