Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading behaviour

Tags:

methods

c#

.net

oop

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.

like image 957
Codex Avatar asked Mar 01 '23 03:03

Codex


1 Answers

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);}
like image 63
Marc Gravell Avatar answered Mar 12 '23 02:03

Marc Gravell