I am trying to find a way to cast a class to its superclass and still use the methods and properties that the class exposes. Check the below code;
public class Car
{
}
public class Audi : Car
{
private int _Mileage;
public int Mileage
{
get { return _Mileage; }
set { _Mileage = value;}
}
}
public class BMW : Car
{
private int _Mileage;
public int Mileage
{
get { return _Mileage; }
set { _Mileage = value;}
}
}
public class Program
{
//outside this class either a BMW class or Audi class is instantiated
Audi _newCar = new Audi();
// I don't know which one it is so I use a generic type
Car MyCar;
int Mileage;
Program()
{
// Now I cast the unknown class to the car type
MyCar = _newCar;
// Although I know both Audi & BMW have the Mileage property, I cannot use it
Mileage = MyCar.Mileage;
}
}
The Car, Audi, BMW classes are part of the framework and I cannot change those. This framework either returns a Audi or BMW (or one of the many others).
To get the Mileage I do not want to create the exact same method for all the possible brands. However when I cast it to its superclass, I do not have access to the Mileage property anymore...
How should I be tackling this?