Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you are doing is not overriding, but shadowing. The <code>new</code> keyword lets you have a <code>Display</code> method in both the classes <code>BC</code> and <code>DC</code>, but the methods are not related at all, they just have the same name.</p> <p>To override the method you would need to use the <code>virtual</code> keyword for the method in the <code>BC</code> class, and the <code>overrides</code> method in the <code>DC</code> class.</p> <p>When you are shadowing a method, it's the type of the reference that decides which method is used:</p> <pre><code>BC b1; b1 = new BC(); b1.Display(); // Calls the method in BC BC b2; b2 = new DC(); b2.Display(); // Calls the method in BC DC d1; d1 = new DC(); d1.Display(); // Calls the method in DC </code></pre> <p>Overriding the method looks like this:</p> <pre><code>class BC { public virtual void Display() { System.Console.WriteLine("BC::Display"); } } class DC : BC { override public void Display() { System.Console.WriteLine("DC::Display"); } } </code></pre> <p>When overriding a method, the methods are related, and it's the actual type of the object that decides which method is used, not the type of the reference:</p> <pre><code>BC b1; b1 = new BC(); b1.Display(); // Calls the method in BC BC b2; b2 = new DC(); b2.Display(); // Calls the method in DC DC d1; d1 = new DC(); d1.Display(); // Calls the method in DC </code></pre> <p>Another difference between overriding and shadowing, is that when you shadow a method the don't have to be similar at all, the <code>new</code> keyword just tells the compiler that you want to reuse the identifier for something other than in the base class. When overriding a method, the method signatures have to be the same.</p> <p>You can for example shadow a public method that takes a <code>string</code> with something completely different like a private property of the type <code>int</code>:</p> <pre><code>public class X { public void XX(string z) { } } public class Y : X { private new int XX { get; set; } } X x = new Y(); x.XX(); Y y = new Y(); y.XX = 42; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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