views:

109

answers:

2

I have an instance of Type (type). How can I determine if it overrides Equals()?

+5  A: 
private static bool IsObjectEqualsMethod(MethodInfo m)
{
    return m.Name == "Equals"
        && m.GetBaseDefinition().DeclaringType.Equals(typeof(object));
}

public static bool OverridesEqualsMethod(this Type type)
{
    var equalsMethod = type.GetMethods()
                           .Single(IsObjectEqualsMethod);

    return !equalsMethod.DeclaringType.Equals(typeof(object));
}

Note that this reveals whether object.Equals has been overridden anywhere in the inheritance hierarchy of type. To determine if the override is declared on the type itself, you can change the condition to

equalsMethod.DeclaringType.Equals(type)

EDIT: Cleaned up the IsObjectEqualsMethod method.

Ani
I'm curious why you use the Linq with the IsObejectEqualsMethod when you could call type.GetMethod("Equals", new Type[] { typeof(object } )Is there some benefit or behavior I'm missing? Or is it just to be Linq-y?
Hounshell
@Hounshell: For a second, I was wondering why myself, but I just remembered. If the type contains a hiding `public new bool Equals(object obj)`, we would be reasoning about the wrong method. I agree the current technique I am using to deal with this is not great, but do you know of a better solution?
Ani
A: 

If you enumerate all methods of a type use BindingFlags.DeclaredOnly so you won't see methods which you just inherited but not have overridden.

codymanix