Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

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

1.00/5 (1 vote)
6 May 2010CPOL 7.5K  
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

C#
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 !

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)