A simple question about overloading

By Roy Osherove In .Net Original

Markdown version

Historical article · Originally published January 5, 2005; technical details may be outdated.

Given 3 classes: PersonBase, Employee and Manager:

class PersonBase { }

class Employee : PersonBase { }

class Manager : Employee { }

 

and given the following  methods:

 

public void Loop()

 {

     PersonBase[] people = new PersonBase[]{

                                 new PersonBase(),

                                 new Employee(),

                                 new Manager()

                                 };

 

     foreach (PersonBase pb in people)

     {

         doSomething(pb);

     }

 }

 

 

 void doSomething(PersonBase p)

 {

     Console.WriteLine("PersonBase");

 }

 void doSomething(Employee e)

 {

     Console.WriteLine("Employee");

 }

 void doSomething(Manager m)

 {

     Console.WriteLine("Manager");

 }

 

Why does only the first of the three “doSomething” overloads get called for all the objects in the array?

How could you force those methods to get called?

(Ignore the various class factory solutions out there.)

More in .Net Original

All posts in .Net Original