How does GetType() knows the type of a derived class?

c#

Solution

The execution-time type is part of the data of the object itself. It's almost like it's a hidden read-only field in `System.Object`, and `GetType()` just returns the value of that field. (It's not quite that simple, but that's a reasonable approximation.)

Note that this information is necessary for the CLR to work out where to dispatch virtual methods - so if you were thinking it would work if `GetType` were virtual, ask yourself how the CLR would know which implementation to call.

Problem

Why this works: ``` Object o = "my string"; Console.WriteLine(o.GetType()); ``` Output: ``` System.String ``` This would make sense if the function call was dispatched to the `String` class, but it didn't since `GetType()` is not virtual.

Original source

Related problems