Lessons in this course (11)

9. Type loading, method calls and virtual dispatch

Intermediate★ Must knowLesson 9 of 11
  • When a type is first used, the CLR loads its metadata and builds an EEClass (static type info) and a MethodTable (per-type runtime structure: size, base type, interfaces, vtable of method slots).
  • Static constructor (static Foo() { }) runs once before first use of the type (thread-safe, guaranteed by the CLR).
  • Non-virtual call: direct call to the method's code address (after JIT).
  • Virtual call: load the object's MethodTable pointer → read the slot for that method → call it. Overrides replace the slot in the derived type's vtable — that's runtime polymorphism.
  • Interface call: resolved through virtual stub dispatch (cached per call site).
  • Sealed classes and the JIT's devirtualisation (helped by PGO) turn virtual calls into direct calls and allow inlining — a reason to mark classes sealed when not designed for inheritance.
  • Generics: for reference-type arguments the JIT shares one native implementation (List<string> and List<Customer> share code); for value types it generates specialised code (List<int>, List<double>) — no boxing and full speed.