How is object.GetType()
implemented in .NET?
3 Answers
It's implemented in the runtime itself, so there is no C# source-code for it.
[MethodImpl(MethodImplOptions.InternalCall)]
public extern Type GetType();
MethodImplOptions.InternalCall
is used for functions which have a "magical" implementation inside the runtime itself.
For the normal .net implementation you won't find it at all since its closed source. With Rotor or Mono you'll most likely find in their c/c++ runtime source-code.
I assume it just uses the marker pointer at the beginning of each instance to get to the class information which then contains a field to get to the managed Type
instance, possibly creating it on demand.

- 106,488
- 23
- 218
- 262
-
by runtime, do you mean in **clr.dll** (a.k.a **Common Language Runtime**) ? – Ehsan Sajjad Dec 29 '16 at 15:49
-
1@EhsanSajjad https://stackoverflow.com/questions/11161120/whats-the-point-of-methodimploptions-internalcall – AFract May 04 '22 at 12:29
I've found an article that explains how Object.GetType()
works in great detail:
How does Object.GetType() really work?
The source code mentioned in this article is now open source in dotnet/runtime on GitHub.

- 57
- 7
-
1Try include the answerin the thread since links can be down in the future. – ytan11 May 06 '22 at 06:44
I suspect this is implemented as part of the engine itself, so it is entirely possible that the "source code" for this is c++ and not published (except perhaps for mono etc).
Either way: I can't think of a scenario where you would need this... If you want to know how the type metadata is associated with the object, look at the CLI spec - ECMA335

- 1,026,079
- 266
- 2,566
- 2,900
-
so the GetType source code resides in the Common Language Runtime ? – Ehsan Sajjad Dec 29 '16 at 15:49