Extension method for copying properties renders an object to another, on the first try

I am trying to write an extension method that I can use to copy values ​​from one property of an object to another object of a different type if the names and types of the properties are exactly the same.

This is what I have:

public static T CopyFrom<T>(this T toObject, object fromObject)
    {
        var fromObjectType = fromObject.GetType();
        var fromProperties = fromObjectType.GetProperties();

        foreach (PropertyInfo toProperty in toObject.GetType().GetProperties())
        {
            PropertyInfo fromProperty = fromObjectType.GetProperty(toProperty.Name);

            if (fromProperty != null) // match found
            {
                // check types
                var fromType = fromProperty.PropertyType.UnderlyingSystemType;
                var toType = toProperty.PropertyType.UnderlyingSystemType;

                if (toType.IsAssignableFrom(fromType))
                {
                    toProperty.SetValue(toObject, fromProperty.GetValue(fromObject, null), null);
                }
            }
        }

        return toObject;
    }

      

This works fine for unsafe types, but Nullable<T>

returns false when I call

toType.IsAssignableFrom(fromType)

      

because its type is Nullable<T>

not a base type T

.

I read here that I GetType()

have to unpack Nullable<T>

so that it returns T

, but if I call this to PropertyInfo.PropertyType

I get ReflectedMemberInfo

, not the type T

im looking for.

I think I am missing something obvious here, so I thought I would throw it at SO for advice.

Does anyone have any ideas?

UPDATE: here is the final method for anyone looking for this.

 public static T CopyFrom<T>(this T toObject, object fromObject)
    {
        var fromObjectType = fromObject.GetType();

        foreach (PropertyInfo toProperty in toObject.GetType().GetProperties())
        {
            PropertyInfo fromProperty = fromObjectType.GetProperty(toProperty.Name);

            if (fromProperty != null) // match found
            {
                // check types
                var fromType = Nullable.GetUnderlyingType(fromProperty.PropertyType) ?? fromProperty.PropertyType;
                var toType = Nullable.GetUnderlyingType(toProperty.PropertyType) ?? toProperty.PropertyType;

                if (toType.IsAssignableFrom(fromType))
                {
                    toProperty.SetValue(toObject, fromProperty.GetValue(fromObject, null), null);
                }
            }
        }

        return toObject;
    }

      

+2


a source to share


1 answer


You are looking for Nullable.GetUnderlyingType

.

For instance:



toType = Nullable.GetUnderlyingType(toType) ?? toType;

      

+2


a source







All Articles