Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if the MethodInfo is an override of the base method

I'm trying to determine if the MethodInfo object that I get from a GetMethod call on a type instance is implemented by the type or by it's base.

For example:

Foo foo = new Foo();
MethodInfo methodInfo = foo.GetType().GetMethod("ToString",BindingFlags|Instance);

the ToString method may be implemented in the Foo class or not. I want to know if I'm getting the foo implementation?

Related question

Is it possible to tell if a .NET virtual method has been overriden in a derived class?

like image 613
Ralph Shillington Avatar asked Jun 11 '09 17:06

Ralph Shillington


3 Answers

Check its DeclaringType property.

if (methodInfo.DeclaringType == typeof(Foo)) {
   // ...
}
like image 114
mmx Avatar answered Dec 07 '22 23:12

mmx


Instead of using reflection a much faster way is to use delegates! Especially in the new version of the framework the operation is really fast.

    public delegate string ToStringDelegate();

    public static bool OverridesToString(object instance)
    {
        if (instance != null)
        {
            ToStringDelegate func = instance.ToString;
            return (func.Method.DeclaringType == instance.GetType());
        }
        return false;
    }
like image 40
Salvatore Previti Avatar answered Dec 07 '22 23:12

Salvatore Previti


You'll want to look at the DeclaringType property. If the ToString method comes from Foo, then the DeclaringType will be of type Foo.

like image 31
jasonh Avatar answered Dec 07 '22 23:12

jasonh