This was intended as a comment on a previous answer, but I guess it's too long.
Having a child class with a constructor that takes an instance of a parent class and copies data from it is a fairly widespread standard. One way to minimize the headache that this can cause with multiple levels of inheritance and other classes is to create a protected function that does this work, in this instance we'll call it Assign. Consider that we have three classes, Person
, Employee
, and Manager
. They each inherit from the other in that order.
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
protected void Assign(Person otherPerson)
{
Name = otherPerson.Name;
}
}
Now we define Employee:
public class Employee : Person
{
private int employeeID;
public Employee() { }
public Employee(Person newEmployee) : this()
{
base.Assign(newEmployee);
}
public int EmployeeID
{
get { return employeeID; }
set { employeeID = value; }
}
protected new void Assign(Employee otherEmployee)
{
base.Assign(otherEmployee);
EmployeeID = otherEmployee.EmployeeID;
}
}
Then we follow the same example for Manager:
public class Manager : Person
{
private string department;
public Manager() { }
public Manager(Employee newManager) : this()
{
base.Assign(newManager);
}
public string Department
{
get { return department; }
set { department = value; }
}
protected new void Assign(Manager otherManager)
{
base.Assign(otherManager);
Department = otherManager.Department;
}
}
So the Assign()
method in each class declared new
so that we can change the signature, and is there to provide shallow copy functionality to inherited classes.
Just note that this pattern creates a NEW object that just has the same data as the old object. The old object still exists and existing references won't point to your new object. Actually changing an object's TYPE is not allowed.