title: c# inheritance: casting of parent object to child
body: <p>We know that it is not possible to cast a parent object to one of its child classes. </p>
  
  <p>So what is a good approach to solve the following problem:
  Let's say I've got a parent class "Person" and two child classes: Customer and Employee. Note that the Person class is <strong>not</strong> abstract (meaning it can be instanciated).
  Now I got the following method signature:</p>
  
  <pre><code>public Person GetPersonById(long id)
  </code></pre>
  
  <p>This makes it possible to either return a Person, or one of its child classes.
  If I use this method, I can check via GetType() whether if it's a child or not. However, I can not easily access the fields/methods specific to the child class because I can't just cast it. 
  One approach would be to implement a constructor for each child class that takes the parent class as parameter and returns a new child class-instance. This has the drawback that I still would have a lot of duplicate code (because I have to assign every parent-field in every child as well).</p>
  
  <p>Another approach I can think of would be to change the method to this:</p>
  
  <pre><code>public object GetPersonById(long id)
  </code></pre>
  
  <p>That way, I could return any class. I'd just check the type of the returned class and then cast it properly. But somehow, this approach seems dirty.</p>
  
  <p>Does anybody have a better way to do this?</p>