Creating a derived object from an existing base object in .net

Stupid question.

Lets say that I have a bunch of objects with fields filled with data, and I have a type of employee that comes from a person’s class and has additional fields related to the fact that he is an employee. How to get an employee object for a specific object of an existing person? For example, how to transfer an object to a person to an employee?

+4
source share
1 answer

If the person was created as an employee, simply click:

Person person = new Employee(); // for some reason ... Employee emp = (Employee)person; 

If a person is just a person: you cannot; you can force the employee to encapsulate Person - or you can copy the fields:

 class Employee { // encapsulation private readonly Person person; public Person {get {return person;}} public Employee(Person person) {this.person = person;} public Employee() : this(new Person()) {} } 

or

 class Employee : Person { // inheritance public Employee(Person person) : base(person) {} public Employee() {} } class Person { public Person(Person template) { this.Name = template.Name; // etc } public Person() {} } 
+5
source

All Articles