0

Consider the following few classes and interfaces :

class Program
{
    interface I { void foo(); }

    abstract class A : I
    {
        public virtual void foo() { Console.WriteLine("A"); }
    }

    class B : A
    {
        public new virtual void foo() { Console.WriteLine("B"); }
    }

    class C : B
    {
        public override void foo() { Console.WriteLine("C"); }
    }

    static void Main(string[] args)
    {
        var c = new C();
        (c as I).foo();
        (c as A).foo();
        (c as B).foo();
    }
}

It outputs :

A A C

where I would (naively) expect "C C C"

if indeed I replace "new virtual" by "override" in class B, that is what I get.

In the MSIL, I get

.method public hidebysig newslot virtual instance void foo () cil managed 

instead of

method public hidebysig virtual instance void foo () cil managed 

What does "new virtual" on a method?

Ho can you explain the behavior of my program?

Regis Portalez
  • 4,675
  • 1
  • 29
  • 41
  • 1
    `new` keyword doesn't override, it signifies a new method that has nothing to do with the base class method. So calls to A will resolve to A since there is no override for it – user2321864 Jan 16 '19 at 09:17
  • In Visual Studio, first remove the `new` keyword from the `B` declaration of `foo`. Then do a `Rename...` action on that `foo` and rename it `Bfoo`. Now look at what got renamed where. `new` says "I know my base class has a method with this same name, but I want to give a *completely different method* that name". That new method bears no relation to the old method (other than bearing the same name) – Damien_The_Unbeliever Jan 16 '19 at 09:19

0 Answers0