C Sharp Type Comparison

From Leo's Notes
Last edited on 2 June 2013, at 04:59.

When comparing object/class types, rather than using typeof(), use TypeHandle.

RuntimeTypeHandle t1 = typeof(ClassName).TypeHandle;
RuntimeTypeHandle t2 = Type.GetTypeHandle(objectName);

if (t1.Equals(t2)) {
 // they are the same type
}

The justification is that TypeHandle is a wrapper around an unmanaged pointer to the type which can be compared directly rather than creating the Type object in the case of the 'is' operator.

see: http://blogs.msdn.com/b/vancem/archive/2006/10/01/779503.aspx