Copy Entity's Members to a new one dynamically using Reflection





1.00/5 (1 vote)
In order to copy an object to a new one and avoiding assigning every member to it equivalent value, you can use this to loop dynamically over every property inside the object and return the value in order to assign it to the new instance public static Employee CopyEmployee(Employee...
In order to copy an object to a new one and avoiding assigning every member to it equivalent value, you can use this to loop dynamically over every property inside the object and return the value in order to assign it to the new instance
public static Employee CopyEmployee(Employee empToCopyFrom)
{
Employee newEmp = new Employee();
//Loop through all employee's members and copy the value to a new instance
foreach (System.Reflection.PropertyInfo propInfo in typeof(Employee).GetProperties())
{
//Get prop value
object valueToCopy = propInfo.GetValue(empToCopyFrom, null);
//Set the prop value
propInfo.SetValue(newEmp, valueToCopy, null);
}
return newEmp;
}
Hope this helped
Enjoy !