Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the use case for C# allowing to use new on a virtual method?
    text
    copied!<p>Being mainly a Java developer, I was a bit surprised by the result when I one day accidentally used <em>new</em> keyword instead of <em>override</em>.</p> <p>It appears that the <em>new</em> keyword removes the "virtualness" of the method at that level in the inheritance tree, so that calling a method on an instance of child class that is downcasted to the parent class, will not resolve to the method implementation in the child class.</p> <p>What are the practical use cases for this behavior? </p> <p>Clarification: I understand the use of new when parent is not virtual. I'm more curious why the compiler allows new and virtual to be combined.</p> <p>The following example illustrates the difference:</p> <pre><code>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(); } } </code></pre> <p>This produces the following output:</p> <pre><code>Calling FooBar:AAA FooBar:AAA Calling FooBar:CCC Bar:CCC Calling Bar:AAA Bar:AAA Calling Bar:CCC Bar:CCC </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload