Mostly a Java developer, I was a little surprised at the result when I once accidentally used a new keyword once instead of overriding it.
It seems that the new keyword removes the “virtuality” of the method at this level in the inheritance tree, so that calling the method on an instance of the child class that is omitted from the parent class will not allow the implementation method in the child class.
What are practical examples of using this behavior?
Explanation: I understand the use of the new when the parent is not virtual. I am more curious why the compiler allows you to combine new and virtual ones.
The following example illustrates the difference:
using System;
public class FooBar
{
public virtual void AAA()
{
Console.WriteLine("FooBar:AAA");
}
public virtual void CCC()
{
Console.WriteLine("FooBar:CCC");
}
}
public class Bar : FooBar
{
public new void AAA()
{
Console.WriteLine("Bar:AAA");
}
public override void CCC()
{
Console.WriteLine("Bar:CCC");
}
}
public class TestClass
{
public static void Main()
{
FooBar a = new Bar();
Bar b = new Bar();
Console.WriteLine("Calling FooBar:AAA");
a.AAA();
Console.WriteLine("Calling FooBar:CCC");
a.CCC();
Console.WriteLine("Calling Bar:AAA");
b.AAA();
Console.WriteLine("Calling Bar:CCC");
b.CCC();
Console.ReadLine();
}
}
This leads to the following conclusion:
Calling FooBar:AAA
FooBar:AAA
Calling FooBar:CCC
Bar:CCC
Calling Bar:AAA
Bar:AAA
Calling Bar:CCC
Bar:CCC