Created
September 2, 2019 05:50
-
-
Save ankitkanojia/76e6963b14374230bf44c5004ccdf3bd to your computer and use it in GitHub Desktop.
Copy property function to copy all properties from one object to another using reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Common function which is use to copy or make a clone of one object to another with datatype and value | |
public static void CopyProperties<TSelf, TSource>(this TSelf self, TSource source) | |
{ | |
try | |
{ | |
var sourceAllProperties = source.GetType().GetProperties(); | |
foreach (var sourceProperty in sourceAllProperties) | |
{ | |
var selfProperty = self.GetType().GetProperty(sourceProperty.Name); | |
if (selfProperty == null) continue; | |
var sourceValue = sourceProperty.GetValue(source, null); | |
selfProperty.SetValue(self, sourceValue, null); | |
} | |
} | |
catch (Exception) | |
{ | |
throw; | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sample Employee class declaration | |
public class Employee | |
{ | |
public int EmployeeID { get; set; } | |
public string EmployeeName { get; set; } | |
public Address ContactAddress { get; set; } | |
} | |
// sample Employee's Address class declaration | |
public class Address | |
{ | |
public string Address1 { get; set; } | |
public string City { get; set; } | |
public string State { get; set; } | |
public string ZipCode { get; set; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Employee employee = new Employee(); | |
employee.EmployeeID = 100; | |
employee.EmployeeName = "John"; | |
employee.ContactAddress = new Address(); | |
employee.ContactAddress.Address1 = "Park Ave"; | |
employee.ContactAddress.City = "New York"; | |
employee.ContactAddress.State = "NewYork"; | |
employee.ContactAddress.ZipCode = "10002"; | |
Employee employeeCopy = new Employee(); | |
//copy all properties from employee to employeeCopy | |
CopyProperties(employee, employeeCopy); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment