views:

88

answers:

2

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?

+1  A: 

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
+1  A: 

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