Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the compiler cast automatically without going further in the inheritance?

Tags:

While I try to run following code snippet, it’s executing wrong overload method. I'm confused why it does that? [testB.TestMethod(testValue) method execute the public double TestMethod(double value) method]

public class TestA {     public int TestMethod(int value)     {         return value;     } }  public class TestB : TestA {     public double TestMethod(double value)     {         return value;     } }  static void Main( string[] args ) {     TestB testB = new TestB();      int testValue = 3;      testB.TestMethod(testValue); } 

Do you have any idea about this ?

Is there are any way to call TestA class method via the TestB instance without cast as TestA.?

But it is not happen in JAVA and C++

like image 897
Thilina H Avatar asked Oct 01 '13 09:10

Thilina H


1 Answers

From the specification, under "Overload Resolution":

...and methods in a base class are not candidates if any method in a derived class is applicable (§7.6.5.1).

like image 153
Marc Gravell Avatar answered Sep 22 '22 21:09

Marc Gravell