10

Possible Duplicate:
Detect if a method was overridden using Reflection (C#)

Is there a way to tell if a method is an override? For e.g.

public class Foo
{
    public virtual void DoSomething() {}
    public virtual int GimmeIntPleez() { return 0; }
}

public class BabyFoo: Foo
{
    public override int GimmeIntPleez() { return -1; }
}

Is it possible to reflect on BabyFoo and tell if GimmeIntPleez is an override?

Community
  • 1
  • 1
Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336

2 Answers2

14

Test against MethodInfo.GetBaseDefinition(). If the function is an override, it will return a different method in a base class. If it's not, the same method object will be returned.

When overridden in a derived class, returns the MethodInfo object for the method on the direct or indirect base class in which the method represented by this instance was first declared.

zildjohn01
  • 11,339
  • 6
  • 52
  • 58
  • 3
    +1 because you are the first one mentioning the GetBaseDefinition method, which I think is the correct way to figure out whether a method is an override. – Ciprian Bortos May 08 '11 at 04:34
4

You can use MethodInfo.DeclaringType to determine if the method is an override (assuming that it's also IsVirtual = true).

From the documentation:

...note that when B overrides virtual method M from A, it essentially redefines (or redeclares) this method. Therefore, B.M's MethodInfo reports the declaring type as B rather than A, even though A is where this method was originally declared...

Here's an example:

var someType = typeof(BabyFoo);
var mi = someType.GetMethod("GimmeIntPleez");
// assuming we know GimmeIntPleez is in a base class, it must be overriden
if( mi.IsVirtual && mi.DeclaringType == typeof(BabyFoo) )
    { ... }
LBushkin
  • 129,300
  • 32
  • 216
  • 265
  • My comment comes a bit late, but here it is. I don't think this solution will do because the BabyFoo type may declare its own virtual method with the same name but different parameters. This solution will not detect that. – Ciprian Bortos May 08 '11 at 04:32