Whats the difference between RuntimeTypeHandle and Type?
-
09-06-2019 - |
Question
And why would I use one over the other in my code?
Solution
Caution: This answer appears to be out of date. It was posted before .NET 4 became available, which apparently introduced some optimizations regarding
Type
and thus rendered the information in this answer obsolete. See this more recent answer for details.
According to this blog post (from 2006) by Vance Morrison, RuntimeTypeHandle
is a value type (struct
) that wraps an unmanaged pointer, so Type.GetTypeHandle(obj).Equals(anotherHandle)
is faster to use for strict "is exactly the same type" comparisons than obj.GetType().Equals(anotherType)
— the latter creates System.Type
instances which are, apparently, heavier.
However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.
OTHER TIPS
In .NET 4.0 Beta 1 RuntimeTypeHandle
just wraps RuntimeType
.
It seems all benefits of using it as a cheap Type
proxy have gone.
Evidence for the above claim:
- Microsoft's Reference Source for the
System.RuntimeTypeHandle
type shows that this type is indeed only a wrapper aroundSystem.RuntimeType
these days. - Sandro Magi's 2013 blog article "CLR: The Cost of Dynamic Type Tests"
contains a benchmark and a final note showing that the supposed performance benefits of
RuntimeTypeHandle
are gone in .NET 4.