Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Overloaded method invocation with Inheritance [duplicate]

I wonder what is the reason for the invocation of the method that prints "double in derived". I didn't find any clue for it in the C# specification.

public class A
{
    public virtual void Print(int x)
    {
        Console.WriteLine("int in base");
    }
}

public class B : A
{
    public override void Print(int x)
    {
        Console.WriteLine("int in derived");
    }
    public void Print(double x)
    {
        Console.WriteLine("double in derived");
    }
}



B bb = new B();
bb.Print(2);
like image 769
Gal Cohen Avatar asked May 01 '13 12:05

Gal Cohen


1 Answers

Straight from the C# spec (7.5.3 Overload resolution):

the set of candidates for a method invocation does not include methods marked override (§7.4), and methods in a base class are not candidates if any method in a derived class is applicable (§7.6.5.1).

In your example, the overriden Print(int x) is not a candidate and Print(double x) is applicable, so it is picked without a need to consider the methods in the base class.

like image 100
Eren Ersönmez Avatar answered Oct 22 '22 12:10

Eren Ersönmez