I have the following code sample :
public class Base
{
public virtual void MyMethod(int param)
{
Console.WriteLine("Base:MyMethod - Int {0}", param);
}
}
public class Derived1 : Base
{
public override void MyMethod(int param)
{
Console.WriteLine("Derived1:MyMethod - Int {0}", param);
}
public void MyMethod(double param)
{
Console.WriteLine("Derived1:MyMethod - Double {0}", param);
}
}
class Program
{
static void Main(string[] args)
{
Base objB = new Base();
objB.MyMethod(5);
Base objBD = new Derived1();
objBD.MyMethod(5);
Derived1 objD = new Derived1();
objD.MyMethod(5);
Console.ReadLine();
}
}
The output of the above code is as follows:
Base:MyMethod - Int 5
Derived1:MyMethod - Int 5
Derived1:MyMethod - Double 5
For the third invocation of 'MyMethod' using 'objD' why is the 'DOUBLE' overload being used when I am actually passing it an INT.
The second invocation using 'objBD' seems to behave correctly. Please suggest.
Oddly, I was discussing this with Jon the other evening! There is a precedence issue - the overridden method is defined in the base-class, so for "best method" purposes, the overload (even with an implicit cast) is preferable, since it is defined in the most-specific type (the subclass).
If you re-declared the method (new
), then it would get precedence, but you can't override
and new
a method with the same name and signature in the same type - you'd have to add an extra level of inheritance to achieve this.
The exact logic for this is detailed in 14.5.5 and 14.4.2 of ECMA 334 v4.
Basically, to make the base method callable, you'll either have to cast to the base-type, or add a shim method:
public void MyMethod2(int param) {base.MyMethod(param);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With