Search code examples
c#clr

Why is this virtual method called?


I write a base class and two derived classes:

class Base
    {
        public virtual void fn()
        {
            Console.WriteLine("base fn");
        }
    }

class Derived1 : Base
    {
        public override void fn()
        {
            Console.WriteLine("derived1 fn");
        }
    }

class Derived2 : Derived1
    {
        public new void fn()
        {
            Console.WriteLine("derived2 fn");
        }
    }

then create an instance of derived2, referenced by a Base variable. Then call the fn() method:

class Program
    {
        static void Main(string[] args)
        {
            Base b = new Derived2();
            b.fn();
            Console.Read();
        }
    }

the result is that the fn() of Derived1 Class is called.

As far as I know, if a virtual method is called, CLR will look for the method in the method table of the runtime type, which is Derived2; if a non-virtual method is called, ClR will look for it in the method table of the variable type which is Base. But why it calls the method of Derived1?

The Answer "Because Derived1 overrides the fn() of Base" is not enough to clarify my puzzle. Please give me more detail.


Solution

  • The virtual method invocation is explained as follows in the reference:

    When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

    Since Derived2 class hides the base method using a "new" keyword, CLR will look for the overriding member in the most derived class, which is Derived1 and executes its method.