frosty

Converting Properties of an inherited class back into the base property

Rate this Entry
Today I had a scenario where we have a class that inherited from a base class. We had a need to use only the base properties. Trying to cast the child class to the base parent didn't work like we needed. The new object was still of a Type of the child.

Example
class BaseAuto
{
int EngineSize{get; set;}
int NumberOfDoors{get; set;}
}

class truck : BaseAuto
{
decimal TowingCapacity{get; set;}
}

So I have a Truck object but I need only the BaseAuto object to use with a DataTemplate in Silverlight.

Truck _truck = new Truck();
BaseAuto _baseTruck = (BaseTruck) _truck;


In the scenario about _baseTruck.GetType() returns as Truck instead of BaseAuto.

So in order to convert the values, I came up with an endpoint which uses Reflection to populate base classes properties.

Code:
 
        private void ConvertClassProperties<T, F>(T convertTo, F convertFrom) where T : class where F : class
        {
            Type _convertToType = convertTo.GetType();
            PropertyInfo[] _toPropInfos = _convertToType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public );
            Type _convertFromType = convertFrom.GetType();
            
            foreach (var prop in _toPropInfos)
            {
                PropertyInfo _convertFromPropInfo = _convertFromType.GetProperty(prop.Name);
 
                // Throw exception if the convertTo doesn't have a matching field as this should never be the case for this method
                if (_convertFromPropInfo == null)
                    AppCommands.RaiseErrorMessage.Send(new AppRaiseErrorEvent(new ArgumentException(string.Format("{0}, convertFrom did not have a matching property", this.GetType().ToString())),
                        string.Format("{0}, convertFrom did not have a matching property")));
 
                prop.SetValue(convertTo, _convertFromPropInfo.GetValue(convertFrom, null), null);
                
            }
        }
To get BaseAuto from Truck, you would use the following code.ConvertClassProperties<BaseAuto, Truck>(_baseTruck, _truck);
Categories
.Net , ‎ Reflection , ‎ .Net 4.0

Comments