I got several questions about calling overloaded(or maybe I should call them hidden) methods in C#. Suppose I have classes as following:
class ParaA {}
class ParaB : ParaA {}
class ParaC : ParaB {}
class TheBaseClass
{
public void DoJob (ParaA a){Console.WriteLine ("DoJob in TheBaseClass is being invoked");}
}
class TheDerivedClass : TheBaseClass
{
public void DoJob (ParaB b){Console.WriteLine ("DoJob in TheDerivedClass is being invoked");}
}
class Test
{
//Case 1: which version of DoJob() is being called?
TheDerivedClass aInstance= new TheDerivedClass ();
aInstance.DoJob(new ParaA ());
//Case 2: which version of DoJob() is being called?
TheBaseClass aInstance= new TheDerivedClass ();
aInstance.DoJob(new ParaA ());
//Case 3: which version of DoJob() is being called?
TheBaseClass aInstance= new TheDerivedClass ();
aInstance.DoJob(new ParaB ());
//Case 4: which version of DoJob() is being called?
TheBaseClass aInstance= new TheDerivedClass ();
aInstance.DoJob(new ParaC ());
}
I hope that I have made myself clear about what I am trying to do. I want to know how will C# search for the ‘matched’ version of method to invoke, when the parameters provided by the invoker do not perfectly match any signature but are compatible with some signatures. It makes me even more confused when methods are not just overloaded within a class, but also hidden, or overrided, or overloaded by derived classes. The example above does not cover every possible scenario. Is there any term for this?
Thank you guys in advance!
Matthew
I’ve added a few more lines to make the code compile:
The produces the output:
i.e. the base class method is called every time.
In Case 1, it is called because the argument is ParaA, and ParaA is not a ParaB.
In the other cases, it is called because the object instance is of type ‘TheBaseClass’.
Here’s the same code modified to illustrate method overloading:
The output is now:
TheDerivedClass method is invoked everytime, because the object is of type ‘TheDerivedClass’.