timmkrause
timmkrause

Reputation: 3621

Inheritance: Call the correct method at runtime depending on the concrete object

I´ve got the following classes:

public class Person
{
}

public class Employee : Person
{
}

public class Customer : Person
{
}

Some methods that use these classes:

public class OtherClass
{
    public void DoSomething(Employee e)
    {
    }

    public void DoSomething(Customer c)
    {
    }
}

The call:

// People = Collection<Person>.
foreach (var p in People)
    DoSomething(p); // Should call the right method at runtime and "see" if it´s an Employee or a Customer.

The compiler does not allow this. How do I implement this scenario?

Upvotes: 2

Views: 74

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064294

The easiest approach here is polymorphism, i.e.

public class Person
{
    public virtual void DoSomething() {} // perhaps abstract?
}

public class Employee : Person
{
    public override void DoSomething() {...}
}

public class Customer : Person
{
    public override void DoSomething() {...}
}

and use:

foreach (var p in People)
    p.DoSomething();

HOWEVER! If that isn't possible, then cheat:

foreach (var p in People)
    DoSomething((dynamic)p); // TADA!

Another option would be to check the type yourself:

public void DoSomething(Person p)
{
    Employee e = p as Employee;
    if(e != null) DoSomething(e);
    else {
        Customer c = p as Customer;
        if(c != null) DoSomething(c);
    }
}

Upvotes: 4

Related Questions