Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic question on method overloading

Tags:

c#

If I have a class SubOfParent which is a sub-class of Parent, and two methods:

 public static void doStuff(Parent in) {}

 public static void doStuff(SubOfPArent in) {}

why does the first doStuff get called when I pass a SubOfParent type object?

Thanks for any insight on this!

like image 508
Bruno Antunes Avatar asked Jul 16 '10 13:07

Bruno Antunes


4 Answers

Parent p = new SubOfParent();
SubOfParent s = new SubOfParent();

doStuff(p); //calls doStuff(Parent in)
doStuff(s); //calls doStuff(SubOfParent in)

//If you're working with a parent but need to call the subclass, you need to upcast it.
dostuff(p as SubOfParent);
like image 158
Mark H Avatar answered Oct 09 '22 15:10

Mark H


method overloading is done at compile time, not at run time, so you won't see any polymorphism with it. Whatever the calling code knows the type to be is going to specify which method is called.

if you want to call the second method you can either cast to the type SubOfPArent or you can instead put those methods into the classes and then call it to get polymorphism:

public class Parent 
{
  public virtual void doStuff() {}
}

public class SubOfPArent : Parent
{
  public override void doStuff() {}
}

...

Parent obj = getASubOfPArent();
obj.doStuff();
like image 45
tster Avatar answered Oct 09 '22 15:10

tster


You probably called the method with a variable of type Parent.

Since method overloads are resolved at compile time, the compiler can only select an overload based on the static compile-time types of the parameters.

Therefore, even though your variable might actually contain a SubOfParent instance at runtime, the compiler doesn't know that and will therefore choose the first overload.

Virtual methods, by contrast, are resolved at runtime based on the actual type of the instance involved.
Therefore, had SubOfParent overridden a virtual method, calling that method on a variable of type Parent would correctly call the overridden method if the instance is in fact of type SubOfParent.

like image 4
SLaks Avatar answered Oct 09 '22 13:10

SLaks


I think you are casting to Parent in your code, or otherwise providing a Parent type. So I think the behaviour is correct and what you are expecting to happen is incorrect.

It is correct that both overloads are valid for a SubOfParent reference, but the overload resolution logic will look for more specific methods and should therefore find the most specific overload.

SubOfParent p = new SubOfParent();

doStuff((Parent)p); // Calls base overload
doStuff(p); // Calls specific overload
like image 2
Adam Houldsworth Avatar answered Oct 09 '22 13:10

Adam Houldsworth