I had this issue today myself, and realized that a solution might be possible using Reflection and then instantiating a new BaseClass object and then copying the values from the properties of the SubClass object onto the BaseClass object (in this so called extension method).
I can't fully remembered what I googled in order to get this code (thanks to our very special friend Google Gemini) :) But I think it was something like 'how do I convert an object from one type to another that have the same properties using reflection".
Anyways, this is the code it gave me :) Its quite useful. Hopefully you will find it useful too :)
Essentially the idea is the 'object source' is your SubClass, and then you convert it to a T = Baseclass.
public static T ConvertTo<T>(this object source) where T : new()
{
if (source == null)
{
return default(T);
}
T target = new T();
Type sourceType = source.GetType();
Type targetType = typeof(T);
foreach (PropertyInfo sourceProperty in sourceType.GetProperties())
{
PropertyInfo targetProperty = targetType.GetProperty(sourceProperty.Name);
if (targetProperty != null && targetProperty.CanWrite && sourceProperty.CanRead)
{
// Ensure the types are compatible or convertible
if (targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType) ||
(sourceProperty.PropertyType != targetProperty.PropertyType &&
CanConvert(sourceProperty.PropertyType, targetProperty.PropertyType)))
{
try
{
object value = sourceProperty.GetValue(source);
object convertedValue = Convert.ChangeType(value, targetProperty.PropertyType);
targetProperty.SetValue(target, convertedValue);
}
catch (InvalidCastException)
{
// Handle cases where direct conversion might fail, e.g., custom types
// You might add more sophisticated mapping here or log the error.
}
}
}
}
return target;
}
private static bool CanConvert(Type sourceType, Type targetType)
{
// Simple check for common convertible types, can be extended for more complex scenarios
return (sourceType == typeof(string) && (targetType == typeof(int) || targetType == typeof(double))) ||
(sourceType == typeof(int) && (targetType == typeof(string) || targetType == typeof(double))) ||
(sourceType == typeof(double) && (targetType == typeof(string) || targetType == typeof(int)));
}