I have two objects of the same type and you need to copy the property values from one object to another. There are two options:
Use reflection, go through the properties of the first object and copy the values.
Serialize the first object and deserialize the copy.
Both work for my requirement, the question is, what should I use in terms of speed (cost)?
Example
class Person { public int ID { get; set; } public string Firsthand { get; set; } public string LastName { get; set; } public int Age { get; set; } public decimal Weight { get; set; } }
You must copy the property values from Person p1 to Person p2 .
For this simple example, which method is faster?
Update
For serialization, I use the ObjectCopier suggested here: Deep cloning objects
For reflection, I use this code:
foreach (PropertyInfo sourcePropertyInfo in copyFromObject.GetType().GetProperties()) { PropertyInfo destPropertyInfo = copyToObject.GetType().GetProperty(sourcePropertyInfo.Name); destPropertyInfo.SetValue( copyToObject, sourcePropertyInfo.GetValue(copyFromObject, null), null); }
c # serialization deserialization deep-copy shallow-copy
net_prog
source share