I have an instance of Type (type). How can I determine if it overrides Equals()?
Asked
Active
Viewed 632 times
5
-
1Why do you need to know that? – Matti Virkkunen Sep 02 '10 at 17:31
-
I'm just playing w/ Reflection and can't figure it out. I've spent my time budget, but I'm punting to the smart people now. – lance Sep 02 '10 at 17:34
-
Related question: http://stackoverflow.com/questions/982347/how-to-determine-if-the-methodinfo-is-an-override-of-the-base-method – Steve Guidi Sep 02 '10 at 17:42
-
@Matti - Unit testing perhaps? It can be useful to know if a type *should* override Equals(), but hasn't. – Doug Nov 28 '11 at 16:24
2 Answers
8
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
- 111,048
- 26
- 262
- 307
-
1I'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 Sep 04 '10 at 10:45
-
@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 Sep 04 '10 at 11:35
-
Great answer. Much shorter than my own, and still passes all my strange test cases. Tests with method hiding: http://nopaste.info/bd9b052f8d_nl.html – CodesInChaos Dec 27 '11 at 17:44
-1
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
- 28,510
- 21
- 92
- 151
-
Except that with `BindingFlags.DeclaredOnly` you will _also_ not see methods which _have_ been overridden. The override is not considered to be a "declaration" of the method per se; the member can be declared just once, in the least-derived type where it appears. In other words: this answer completely fails to address the question. – Peter Duniho Sep 03 '19 at 05:41