inheritance and instantiation

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Peter

    inheritance and instantiation

    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)pers on;
    employee.Compan y = "my co";

    but I soon found out that won't do.


    Thanks,
    Peter
  • Marc Gravell

    #2
    Re: inheritance and instantiation

    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

    Comment

    • Clint

      #3
      Re: inheritance and instantiation

      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.Activato r.CreateInstanc e()




      Comment

      • Marc Gravell

        #4
        Re: inheritance and instantiation

        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

        Comment

        Working...