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...
SetCarPropertiesmethod in theCarclass, and have it overridden in the child classSuperCar.