Cleo
Cleo

Reputation: 93

c# inheritance: casting of parent object to child

We know that it is not possible to cast a parent object to one of its child classes.

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 not abstract (meaning it can be instanciated). Now I got the following method signature:

public Person GetPersonById(long id)

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).

Another approach I can think of would be to change the method to this:

public object GetPersonById(long id)

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.

Does anybody have a better way to do this?

Upvotes: 1

Views: 12946

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

You can cast Person to Customer if it really is a Customer:

var customer = person as Customer;
if(customer != null)
{
    // the person was really a Customer
}

If you'd like you could create three methods instead of one:

public Person GetPersonById(long id)
public Customer GetCustomerById(long id)
public Employee GetEmployeeById(long id)

Or use Generics (but I feel bad about generics in that particular case):

public T GetPersonById<T>(long id) where T : Person

And call it:

var person = GetPersonById<Employee>(123);

But you still need to specify what you're trying to get at call time.

Upvotes: 4

Stochastically
Stochastically

Reputation: 7836

But in fact you can cast a parent object to it's child type, IF the object is of that type

Upvotes: 2

David
David

Reputation: 16277

Use "is" keyword

if(instance is ChildClass)
{
    //...
}

Upvotes: 0

Related Questions