0

Suppose I have this code:

BaseClass baseClassVar = new DerivedClass();
baseClassVar.OverloadingMethod();

Both BaseClass and DerivedClass have one method called OverloadingMethod.

If we create an instance of DerivedClass and store it in a BaseClass variable; then call OverloadingMethod, it will call the method in base class.

If so we can assume baseClassVar is a type of BaseClass, and it does sounds logical. But viewing the object in debug or call GetType() actually return a type of DerivedClass. How does it work like that?

Dennis
  • 37,026
  • 10
  • 82
  • 150
Hp93
  • 1,349
  • 3
  • 14
  • 23
  • 1
    Your `OverloadingMethod()` is **not virtual**, in this case there is no vtable entry then you call `BaseClass.OverloadingMethod()` if you have a variable of type `BaseClass` and `DerivedClass.OverloadingMethod()` if you have a variable of type `DerivedClass`. Odd situation you should almost never have in real world (and compiler should emit a warning CS0108 for that unless you explicitly mark it with `new`). – Adriano Repetti Jun 06 '16 at 11:12
  • 3
    This is standard magic in any object-oriented programming language. More obvious when you write `object obj = new DerivedClass();`. Any object reference can be converted to a base class reference. Crystal ball says that you need to lookup `virtual` in your favorite C# language book, overloading means something completely different. – Hans Passant Jun 06 '16 at 11:17
  • Accepted answer from linked question contains good explanation about `virtual`/`new` methods. – Dennis Jun 06 '16 at 11:24
  • I know how to use virtual and overriding to resolve this. I just curious why `GetType()` return `DerivedClass`? If we know it's type is `DerivedClass`, why don't point to the new overloading method, rather than pointing back to base method? – Hp93 Jun 07 '16 at 02:22

0 Answers0