How to copy Collections of different type using Reflection?

Viewed 16

I'm using an extension method to copy properties from an object to another (base on type and name). Below is my current code (inspired from this article). I added some code to accommodate the copy of nullable to their base type if needed but I can't seem to find an elegant way to copy over collections of different types. For instance how to copy a List<T> to an ObservableCollection<T> (where T is the same type in each collection) ? All the collections are always initialized and it is ok to clear them before copy so it may help a bit.

Thank you for your help and guidance.

public static void CopyPropertiesFrom(this object? self, object parent){
    var fromProperties = parent.GetType().GetProperties();
    var toProperties = self.GetType().GetProperties();

    foreach (var fromProperty in fromProperties)
    foreach (var toProperty in toProperties.Where(x => x.SetMethod != null))
        if (fromProperty.Name == toProperty.Name){
            if (fromProperty.PropertyType == toProperty.PropertyType){
                toProperty.SetValue(self, fromProperty.GetValue(parent));
                break;
            }

            //The code below is to accomodate Nullable type and copy properties based on the base type
            if (Nullable.GetUnderlyingType(fromProperty.PropertyType) == toProperty.PropertyType){
                if (fromProperty.GetValue(parent) == null) continue;
                toProperty.SetValue(self, fromProperty.GetValue(parent));
                break;
            }

            if (Nullable.GetUnderlyingType(toProperty.PropertyType) == fromProperty.PropertyType){
                toProperty.SetValue(self, fromProperty.GetValue(parent));
                break;
            }

            if (Nullable.GetUnderlyingType(fromProperty.PropertyType) ==
                Nullable.GetUnderlyingType(toProperty.PropertyType)){
                //This case will be true when from and to are two collections<T>, where T is the same between each collections.
                //However I'm not sure how to detect the type of collections and add the necessary logic to clear/add elements
                toProperty.SetValue(self, fromProperty.GetValue(parent));
                break;
            }
        }
}
0 Answers
Related