Reputation: 1668
How is object.GetType()
implemented in .NET?
Upvotes: 5
Views: 886
Reputation: 57
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.
Upvotes: 2
Reputation: 108790
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.
Upvotes: 8
Reputation: 1062600
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
Upvotes: 1