Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating objects from another object with same properties

Tags:

c#

.net

I have an object in C# with lets say 20 properties and it's part of a datacontract. I also have another business entity with similar properties, which I want to populate from the response object. Is there any way to do this other than assigning each property of one object to the corresponding properties of the other?

like image 665
jyotishka bora Avatar asked Apr 17 '26 13:04

jyotishka bora


2 Answers

Yes, take a look at Automapper

like image 152
Igor Brejc Avatar answered Apr 19 '26 01:04

Igor Brejc


MiscUtil has an answer to this (PropertyCopy) that uses Expression (.NET 3.5) and a static field to cache the compiled delegate (so there is negligible cost per invoke):

DestType clone = PropertyCopy<DestType>.CopyFrom(original);

If you are using 2.0, then probably reflection would be your friend. You can use HyperDescriptor to improve the performance if you need.

like image 20
Marc Gravell Avatar answered Apr 19 '26 03:04

Marc Gravell