user4572253
user4572253

Reputation:

How does GetType() knows the type of a derived class?

Why this works:

Object o = "my string";
Console.WriteLine(o.GetType());

Output:

System.String

This would make sense if the function call was dispatched to the String class, but it didn't since GetType() is not virtual.

Upvotes: 10

Views: 185

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503120

The execution-time type is part of the data of the object itself. It's almost like it's a hidden read-only field in System.Object, and GetType() just returns the value of that field. (It's not quite that simple, but that's a reasonable approximation.)

Note that this information is necessary for the CLR to work out where to dispatch virtual methods - so if you were thinking it would work if GetType were virtual, ask yourself how the CLR would know which implementation to call.

Upvotes: 3

Related Questions