Skip to content

Instantly share code, notes, and snippets.

@ankitkanojia
Created September 2, 2019 05:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ankitkanojia/76e6963b14374230bf44c5004ccdf3bd to your computer and use it in GitHub Desktop.
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
// 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;
}
}
// 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