I have two objects of the same type and need to copy property values from one object to another. There are two options:
Use reflection, navigate through the properties of the first object and copy the values.
Serialize the first object and deserialize a copy.
Both work for my requirement, the question is which do I better use in the 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; }
}
Need to copy property values from Person p1
to Person p2
.
For this simple sample - 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);
}