Derived and base class, can I set the base explicitly?

Watson picture Watson · Jan 28, 2011 · Viewed 19.6k times · Source
public class SuperCar: Car
{
     public bool SuperWheels { get {return true; } }
}

public class Car 
{
     public bool HasSteeringWheel { get {return true;} }
}

How can I set the base class for the derived Supercar?

For example, I want to simply set SuperCars base class like this:

public void SetCar( Car car )
{
SuperCar scar = new SuperCar();
car.Base = car; 
}

Basically, if I have Car objects, I do not want to manually iterate through every property of the car in order to setup the SuperCar oject, which I think is the only way you can do it but if you can do it the other way it would be sooo much better.

Answer

vyengr picture vyengr · Sep 25, 2013

I use something like this in the subclass and it works fine for me:

using System.Reflection;
.
.
.
/// <summary> copy base class instance's property values to this object. </summary>
private void InitInhertedProperties (object baseClassInstance)
{
    foreach (PropertyInfo propertyInfo in baseClassInstance.GetType().GetProperties())
    {
        object value = propertyInfo.GetValue(baseClassInstance, null);
        if (null != value) propertyInfo.SetValue(this, value, null);
    }
}