inheritance and instantiation

  • Thread starter Thread starter Peter
  • Start date Start date
P

Peter

Hi

I have a
class Person : IPerson

and a
class Employee : Person, IEmployee

and an
interface IEmployee : IPerson


Say I have a method like

IPerson GetPerson(long id)
{
return new Person();
}

How do I turn the "Person" object into an "Employee" object?

Do I need to instantiate a new Employee and copy the fields from the
Person object manually (and add the extra data an Employee holds)?

I was hoping I could do something like:
IEmployee employee = (IEmployee)person;
employee.Company = "my co";

but I soon found out that won't do.


Thanks,
Peter
 
IPerson GetPerson(long id)
{

Presumably the ID is used to retrieve the details from some data source.
(pseudo code)

if (ID is an employee) {
return new Employee(ID, Name, SSN etc);
}
if (ID is a manager) {
return new Manager(ID, Name, SSN etc);
}

....and so on. All are derived from Person and as such implement IPerson. A
simple yet classic Factory. Ideally you would not use the if's as I have
done, this will overtime become quite messy. Instead create something
generic where the type (Manager, employee etc) is also sourced for the data
source.

}

See System.Activator.CreateInstance()

http://en.wikipedia.org/wiki/Factory_method_pattern
 
Do I need to instantiate a new Employee and copy the fields from the
Person object manually (and add the extra data an Employee holds)?

Yes. Casting simply tweaks the local variable - it doesn't change the
object. If the object is a Person, it is still a Person regardless of
how you reference it. You cannot change an object's type after
creation. Note that if the GetPerson *returned* an Employee instance
(still returning as IPerson), then the cast would succeed.

Marc
 
As an aside, Clint's example essentially describes a "discriminator".
Many ORM tools (for plumbing your data-access code) will do this for
you. For example, LINQ-to-SQL supports a discriminator property: you
might have a column that is "E", "M" or "P" (for employee, manager and
person) - when fetching records it will automatically create the right
type of object to represent the row you fetched, and when inserting a
record it will automatically add the correct "E"/"M"/"P" value.

Marc
 
Back
Top