C # will allow your call to another implementation, because method calls to an object where the class for this object has its own implementation will be preferable to overridden or inherited.
This can lead to subtle and inaccessible problems, such as those shown here.
For example, try this code (read it first, then compile and execute it), see if it does what you expect from it.
using System; namespace ConsoleApplication9 { public class Base { public virtual void Test(String s) { Console.Out.WriteLine("Base.Test(String=" + s + ")"); } } public class Descendant : Base { public override void Test(String s) { Console.Out.WriteLine("Descendant.Test(String=" + s + ")"); } public void Test(Object s) { Console.Out.WriteLine("Descendant.Test(Object=" + s + ")"); } } class Program { static void Main(string[] args) { Descendant d = new Descendant(); d.Test("Test"); Console.In.ReadLine(); } } }
Note: if you specify a variable of type Base instead of Descendant , the call will switch to another method, try changing this line:
Descendant d = new Descendant();
and run again:
Base d = new Descendant();
So, what could you call Descendant.Test(String) then?
My first attempt looks like this:
public void Test(Object s) { Console.Out.WriteLine("Descendant.Test(Object=" + s + ")"); Test((String)s); }
This did not help me, and instead just called Test(Object) over and over for the possible.
But the following work. Since when we declare the variable d Base , we end up calling the correct virtual method, we can also resort to this trick:
public void Test(Object s) { Console.Out.WriteLine("Descendant.Test(Object=" + s + ")"); Base b = this; b.Test((String)s); }
This will print:
Descendant.Test(Object=Test) Descendant.Test(String=Test)
you can also do this from outside:
Descendant d = new Descendant(); d.Test("Test"); Base b = d; b.Test("Test"); Console.In.ReadLine();
prints the same thing.
But first you need to know about the problem , which is completely different.