12

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);
9
  • msdn.microsoft.com/en-us/library/aa691338%28v=vs.71%29.aspx Commented May 1, 2013 at 12:38
  • I you can decipher the rules of 7.4.2.2 and 7.4.2.3, you're probably cleverer than me, but it will be there somewhere. Commented May 1, 2013 at 12:41
  • @spender, It might be in there, but It's written poorly :). Commented May 1, 2013 at 12:42
  • 3
    This has been answered. See this thread : stackoverflow.com/questions/2821620/… Commented May 1, 2013 at 12:45
  • 1
    @cvraman, that example is slightly different, even if it gives the same result. In that case the integer literal is also of type object (a widening cast is occurring). However in the example given above an implicit cast is taking place (from int to double.) Commented May 1, 2013 at 12:56

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The compiler looks at methods which are freshly-declared in the most derived class (based on the compile-time type of the expression) and sees if any are applicable. If they are, it uses the "best" one available.

See the answer to this question :

Different behaviour of method overloading in C#

2 Comments

Please quote and include a link to the original answer. Thank you.
Added a link to the above answer, where the quote was taken from

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.