Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top