0

I was reading about virtual method tables on wikipedia and I stumbled upon

Whenever a class defines a virtual function (or method), most compilers add a hidden member variable to the class which points to an array of pointers to (virtual) functions called the virtual method table (VMT or Vtable).

However, when I decompile my test code I don't find any member variable in the IL.

I am using latest version of Roslyn to compile (2.6.0).

Here is my test code:

namespace ConsoleApp1
{
    using System;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var a = new Base();
            var b = new Derived();

            a.Say();
            b.Say();
        }
    }

    public class Base 
    {
        public virtual void Say()
        {
            Console.WriteLine($"{this.GetType()}");
        }
    }

    public class Derived : Base
    {
        public override void Say()
        {
            Console.WriteLine($"{this.GetType()}");
        }
    }
}

I suppose I am misunderstanding something here, could you help me what it is?

kuskmen
  • 3,648
  • 4
  • 27
  • 54
  • 2
    overloads/overrides/etc still exist as a concept at the IL level. The compiler creating virtual method tables (if that is indeed the chosen technique used in any particular CLR) is the JIT compiler, the one used at runtime. – Damien_The_Unbeliever Dec 13 '17 at 13:20
  • 5
    That comment box applies to the C++ language. .NET works differently, a class always has a method table, regardless of whether a method is virtual or not. It does multiple jobs, like keeping track whether a method has been just-in-time compiled yet. That table is neither stored nor visible in IL code, it is maintained by the CLR. An object has a pointer to that table, not visible either, part of the object header. That pointer is equivalent to the v-table pointer in C++. [The debugger can show you](https://stackoverflow.com/a/5383926/17034). – Hans Passant Dec 13 '17 at 13:21
  • @Damien_The_Unbeliever, I see so virtual method tables are created at runtime by the JIT ? – kuskmen Dec 13 '17 at 13:26
  • @HansPassant, thanks a lot for that reference! – kuskmen Dec 13 '17 at 13:26
  • 2
    The best way to mentally visualize IL is as the assembly language of a virtual machine, one that is still object-oriented and has a `virtual` keyword. It is the CLR that makes a method behave virtually. Mapping it to C++, IL is produced by the front-end of the compiler, the jitter implement the back-end of the compiler, the one that has the optimizer and generates the machine code. – Hans Passant Dec 13 '17 at 13:30

0 Answers0