typeof
is used when you want to get the Type
instance representing a specific type. GetType
gives the runtime type of the object on which it is called, which may be different from the declared type.
For example:
class A {}
class B : A {}
class Program
{
static A CreateA()
{
return new B();
}
static void Main()
{
A a = CreateA();
Console.WriteLine(typeof(A)); // Writes "A"
Console.WriteLine(a.GetType()); // Writes "B"
}
}
In the above case, within the Main
method, you're dealing with instances of type A
; thus, if you care about the declared type, you would use typeof(A)
. However, the CreateA
method actually returns an instance of a derived class, B
, despite declaring the base class as the return type. If you want to find out about this runtime type, call GetType
on the returned instance.
Edit: Mehrdad's comment points in the right direction. Although typeof
emits a GetTypeFromHandle
call that takes a RuntimeTypeHandle
as parameter, the said parameter would actually correspond to the specific type whose metadata token is on the evaluation stack. In some instances, this token would be there implicitly (due to the current method invocation); otherwise, it can be pushed there explicitly by calling ldtoken. You can see more examples of this in these answers:
Edit2: If you're looking for performance benchmarks, you can refer to Jon Skeet's answer. His results were (for 100 million iterations):
typeof(Test): 2756ms
test.GetType(): 3734ms
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…