I recently needed to know if a virtual method had been overridden in one of my base classes. Making that determination wasn't hard and only required a bit of reflection. I thought the solution might make a good blog entry since I'm looking for something to do on my lunch hour today.
Here is the code, with a description afterwards:
class A
{
public virtual string Foo()
{
if (IsFooOverridden())
return "overridden A";
else
return "A";
}
private bool IsFooOverridden()
{
Type classType = typeof(A);
Type type = base.GetType();
if (type != classType)
{
MethodInfo mi = type.GetMethod(
"Foo",
BindingFlags.Public | BindingFlags.Instance,
null,
new Type[0],
null
);
return mi.DeclaringType != classType;
}
return false;
}
}
// ***********
class B : A
{
public override string Foo()
{
return base.Foo() + " plus B";
}
}
// ***********
class Class1
{
public static void Test()
{
A a = new A();
A b = new B();
string fooA = a.Foo();
string fooB = b.Foo();
}
}
Class "A" is a base class with a single virtual method. Class "B" derives from "A" and overrides that method. The "IsOverridden" method in the "A" class is used to determine whether the "Foo" method has been overridden at runtime. They way it does that is by first comparing the type for the base class with a type known at compile time (in this case the "A" type). If the two types don't match the code assumes that the method is being called from a derived type and goes on to check the type associated with the method. If the "Foo" method has been associated with a type other than the "A" class then we know that the method is being called from an override.
The test method in Class1 creates an instance of "A" and other of "B". It then calls the "Foo" method and saves the result in a variable. If you set a breakpoint just after the calls to "Foo" and run the code you'll see that the "fooA" variable contains "A" and the "fooB" variable contains "overridden A plus B". These results demonstrate how the code in the base class can change depending upon whether the method has been overridden at runtime.
Nothing complicated but I thought someone might be interested.
See ya!