Differences between typeof and GetType

  • Thread starter Thread starter Guest
  • Start date Start date
srkvellanki,

GetType is a call that is made at runtime on an instance of an object.
typeof() is resolved to a call at runtime, but loads the type from the token
for the type. They probably resolve to the same call, it's just that
GetType requires an instance. If I didn't need the instance, I would use
typeof.

Hope this helps.
 
Nicholas Paldino said:
srkvellanki,

GetType is a call that is made at runtime on an instance of an object.
typeof() is resolved to a call at runtime, but loads the type from the
token for the type. They probably resolve to the same call, it's just
that GetType requires an instance. If I didn't need the instance, I would
use typeof.

Hope this helps.

Also be aware that GetType is virtual, and gives you the type of the object,
not the declared type of the reference. That is:

Object o = new String();

typeof(Object) Object type
typeof(o) String type
 
Hi, srkvellanki.
I assume by GetType you mean Type.GetType. The difference between
Object.GetType and typeof has been explained in previous two posts.
typeof is resolved at compile time, so the type has to be either in
current assembly or one of the assemblies it reference to. Type.GetType on
the other hand, resolves the full qualified type name (namespace + assembly
information) at runtime, so it can be used to load types defined in any
assembly that can be located at runtime. Another note about Type.GetType is,
when called with a typename without the defining assembly, it only looks for
the type in calling assembly and mscorlib.dll.

Hope this helps.
Ming Chen
 
Back
Top