Bring your own boxes

The other day, I was looking through the code of the .NET framework code for EqualityComparer<T> in Reflector. This type contains some rather interesting code for constructing a Default instance for each generic instantiation, and it took a while to dig out an old blog post that describes the technique that is used.

private static EqualityComparer<T> CreateComparer()
    Type c = typeof(T);
    if (c == typeof(byte))
        return (EqualityComparer<T>) new ByteEqualityComparer();
    if (typeof(IEquatable<T>).IsAssignableFrom(c))
        return (EqualityComparer<T>) typeof(GenericEqualityComparer<int>).TypeHandle.CreateInstanceForAnotherGenericParameter(c);
    if (c.IsGenericType && (c.GetGenericTypeDefinition() == typeof(Nullable<>)))
        Type type2 = c.GetGenericArguments()[0];
        if (typeof(IEquatable<>).MakeGenericType(new Type[] { type2 }).IsAssignableFrom(type2))
            return (EqualityComparer<T>) typeof(NullableEqualityComparer<int>).TypeHandle.CreateInstanceForAnotherGenericParameter(type2);
    return new ObjectEqualityComparer<T>();
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s