jeudi 20 août 2020

how to copy properties from one object to another with different values C#

I want to copy classA to ClassB,but if ClassB has a value and ClassA is null,it do not copy eg.

  public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public Address ContactAddress { get; set; }
    }

    public class Address
    {
        public string Address1 { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
    }

test eg.

public void TestMethod1()
        {
  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();
            employeeCopy.EmployeeID = 101;
            employeeCopy.EmployeeName = "Tom";
            employeeCopy.ContactAddress = new Address();

            CopyPropertiesTo(employee, employeeCopy);
    }

I want to get the result

employeeCopy EmployeeID=101;

EmployeeName="Tom";

ContactAddress.Address1 = "Park Ave";

ContactAddress.City = "New York";

ContactAddress.State = "NewYork";

ContactAddress.ZipCode = "10002"

I mian if ClassB has value,I will use it,but if ClassB is null and ClassA has value ,copy ClassA's value,I can not write the method "CopyPropertiesTo(employee, employeeCopy)", some body who can help me? thank you!





Aucun commentaire:

Enregistrer un commentaire