65.9K
CodeProject is changing. Read more.
Home

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

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (1 vote)

May 7, 2010

CPOL
viewsIcon

7500

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 !