How to call an overridden method that has overloads?

I have the following simple code

abstract class A { public abstract void Test(Int32 value); } class B : A { public override void Test(Int32 value) { Console.WriteLine("Int32"); } public void Test(Double value) { Test((Int32)1); } } 

When I ran this code, the line Test ((Int32) 1) causes a stack overflow due to infinite recursion. The only possible way to correctly call the correct method (with an integer parameter) that I found is to

 (this as A).Test(1); 

But this is not suitable for me, because both Test methods are public, and I want users to be able to call both methods?

+7
source share
2 answers

Unfortunately, calling A::Test(int) via link B requires some sort of selection. While the C # compiler sees the link through B , it will select the version of B::Test(double) .

A slightly less ugly version is next

 ((A)this).Test(1); 

Another thought, although it has a private method with a different name, which is both transmitted.

 class B : A { public override void Test(int i) { TestCore(i); } public void Test(double d) { TestCore(1); } private void TestCore(int i) { // Combined logic here } } 
+4
source

Enabling method overloading in C # does not always behave as you might expect, but your code behaves according to the specification (I wrote a blog post about this a while ago).

In short, the compiler begins by looking for methods that

  • Has the same name (in your case Test )
  • are declared in type (in your case B ) or one of its base types
  • not declared using override modifier

Please note that the last point. This is actually logical, since virtual methods are resolved at runtime, not compilation time.

Finally, if the type (in this case B ) has a method that is a candidate (which means that the parameters in your call can be implicitly converted to the parameter type of the candidate method), this method will be used. Your overridden method is not even part of the decision-making process.

If you want to call your overridden method, you need to first transfer the object to its base type.

+5
source

All Articles