Given 2 objects A and B of type T, I want to assign the properties’ values in A to the same properties in B without doing an explicit assignment for each property.
I want to save code like this:
b.Nombre = a.Nombre;
b.Descripcion = a.Descripcion;
b.Imagen = a.Imagen;
b.Activo = a.Activo;
doing something like
a.ApplyProperties(b);
Is it possible?
I have a type in
MiscUtilcalledPropertyCopywhich does something similar – although it creates a new instance of the target type and copies the properties into that.It doesn’t require the types to be the same – it just copies all the readable properties from the “source” type to the “target” type. Of course if the types are the same, that’s more likely to work 🙂 It’s a shallow copy, btw.
In the code block at the bottom of this answer, I’ve extended the capabilities of the class. To copy from one instance to another, it uses simple
PropertyInfovalues at execution time – this is slower than using an expression tree, but the alternative would be to write a dynamic method, which I’m not too hot on. If performance is absolutely critical for you, let me know and I’ll see what I can do. To use the method, write something like:(where
Copyis a generic method called using type inference).I’m not really ready to do a full MiscUtil release, but here’s the updated code, including comments. I’m not going to rewrap them for the SO editor – just copy the whole chunk.
(I’d also probably redesign the API a bit in terms of naming if I were starting from scratch, but I don’t want to break existing users…)