When .GetType() method is called upon an object, how does C# know its type?
Whenever a method is executed, the CLR creates a list of all types' static metadata refereed to inside the method, each with a reference to their Type object.
When an object is created (like using the new
operator), the CLR adds a Type object pointer as it allocates the object in the heap, and directs this pointer to the static Type object, which contains information like the name of the type, the namespace, the list of methods and properties it defines, etc.
When GetType
is called on the object it simply returns the reference its Type object points to, which is why even storing the instance into another variable of object
type keeps a correct reference to its original type (the type it was created as).
What if the object is identical to some other object type in the same project?
The type of an object is defined by its name, its namespace and its assembly. You cannot have two classes of the same name within the same namespace, as the compiler will complain of Duplicate definition
. However, as long as they reside on different namespaces, System.Foo.Bar
and System.Bar
they can co-exists.