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) {
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}
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) {
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...