5

How is object.GetType() implemented in .NET?

Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
Glebka
  • 1,420
  • 3
  • 20
  • 37

3 Answers3

8

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
2

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.

Il Harper
  • 57
  • 7
1

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900