Extension Method for copying properties form object to another, with first attempt

Posted by James on Stack Overflow See other posts from Stack Overflow or by James
Published on 2010-05-13T12:35:05Z Indexed on 2010/05/13 12:44 UTC
Read the original article Hit count: 376

Hi All,

Im trying to write an extension method that I can use to copy values from one object property to another object of a different type, as long as the property names and types match exactly.

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 is working great for non boxed types, but Nullable<T> returns false when I call

toType.IsAssignableFrom(fromType)

because its type is Nullable<T> and is not the underlying type T.

I read here that GetType() should unbox the Nullable<T> so it returns T but if I call that on PropertyInfo.PropertyType I get ReflectedMemberInfo and not the type T im looking for.

I think im missing something obvious here, so I thought I would throw it open to SO to get some advice.

Anyone have any ideas?

Thanks,

Jamee

© Stack Overflow or respective owner

Related posts about extension-methods

Related posts about reflection