One of the requirements for using Agatha’s Caching Layer is that your request types must override the Equals and the GetHashCode methods. In order to limit the number of questions i’m going to receive about the caching layer not working correctly the amount of time people will waste on debugging when they don’t override these methods, i wanted to add a check to the initialization of Agatha which makes sure that each cacheable request type indeed overrides Equals and GetHashCode.
I actually had to think about how i could do this, but it turned out to be very simple. The trick is basically to retrieve the MethodInfo of the method you're interested in, and then check the declaring type of that method. If the method has been overridden, the declaring type will equal the type of the class you're checking. If it hasn’t been overridden, the declaring type will be that of one of the base classes:
private static bool CheckIfOverrideExists(Type type, string methodName)
{
var methodInfo = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public);
if (methodInfo == null)
{
return false;
}
return methodInfo.DeclaringType == type;
}
Not sure if there’s a better way to do this (if so, please share) but for now, this is good enough for me.
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #515
Pingback: Find, if a method is overridden in a derived class! « ReflectWorks