Overloading an inherited method

Good day,

When you have a derived class that overloads an existing method, as in:

public class TestBase{

public virtual int TestMethod(int testIntParm){

return 0;

}

}

public class TestDerived : TestBase{

public int TestMethod(double testDoubleParm){

return 1;

}

}

instances of the derived class will call the derived version of the method if it can automatically cast the passed parameter to the type expected by the derived version, even if the base class has a better-matching method signature. For example:

TestDerived testDerived = new TestDerived();

int i = 99;

Console.WriteLine(testDerived.TestMethod(i));

results in 1 (i.e. it ran the version of the method that accepted the double parm even though it was passed an int).

Short of overriding the base class version of the method and calling back to the base, is there any way to handle this situation

Thanks in advance...



Answer this question

Overloading an inherited method

  • Bjorn B

    Even if you override the base method, it would still call the new overload. It's one of the oddities about overload resolution in C# - if there are any "new" signatures in the derived class, the inherited signatures are ignored.

    I think the best thing is not to add overloads, I'm afraid.

    Jon



  • g4rc

    Thanks Jon.

    I should have said newing (not overriding) the base method in the derived class and calling base.method was how we made it work the way we had intended.


  • Overloading an inherited method