views:

103

answers:

2

I would like to copy one object to another object, and the fields with the same names and type to be copied. Perhaps using reflections.

e.g.

object1.Name = object2.Name; object1.Age = object2.Age;

However if object2.Address is not in object1 then it would be ignored and vis-versa.

A: 

See this post , and put a check for the object types before

Gregoire
+1  A: 

I answered a similar question here. The difference is that you want the from and to to have different types and to match properties by name and by type. This is not too hard.

I haven't tested this - but give it a shot

public static class ExtensionMethods
{
    public static void CopyPropertiesTo<T, U>(this T source, U dest)
    {
        var plistsource = from prop1 in typeof(T).GetProperties() where prop1.CanRead select prop;
        var plistdest = from prop2 in typeof(U).GetProperties() where prop2.CanWrite select prop;

        foreach (PropertyInfo destprop in plistdest)
        {
            var sourceprops = plistsource.Where((p) => p.Name == destprop.Name &&
              destprop.PropertyType.IsAssignableFrom(p.GetType()));
            foreach (PropertyInfo sourceprop in sourceprops)
            { // should only be one
                destprop.SetValue(dest, sourceprop.GetValue(source, null), null);
            }
        }
    }
}

}

If you don't like the extension method, you could just rewrite this to be public static void CopyPropertiesTo(object source, object dest);

this should let you do something like this:

Foo foo = new Foo();
Bar bar = GetBar();
bar.CopyPropertiesTo<Bar, Foo>(foo);
plinth
How about if the objects have an IEnumerable, then this is not copied. Can you think of anyway that this can be done?
Coppermill
IEnumerable is a different beast altogether, therefore it should be treated differently.
plinth