When .GetType()
method is called upon an object, how does C# know its type? What if the object is identical to some other object type in the same project? Do they have some sort of unique identification (like GUID) baked into them?
When .GetType() method is called upon an object, how does C# know its type?
In addition to a memory location, the CLR actually stores type information with each and every object.
This is stored in the TypeHandle
. For details, see Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects, in particular, the Type Fundamentals section.
When you call Object.GetType()
on an object, the CLR does a lookup based on the TypeHandle in the object reference, and returns the appropriate type.