I am trying to use reflection to determine which methods a derived class overrides from a base class. It is fairly easy to determine if the method is not overridden, but trying to determine if a method is overridden in a base class, or simply created as virtual in the derived class is what I am trying to accomplish.
So, if Class A has virtual methods Process and Export, and Class B has virtual methods Process(overridden), and Display (new virtual method), I would like the following results when examining Class B;
I only want to deal with the Display method when examining a class that derives from Class B.
Also, you can have an implementation in a virtual method, i.e., virtual methods can have implementations in them. These implementations can be overridden by the subclasses of the type in which the virtual method has been defined.
In C#, a virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overriden in the derived class.
A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.
A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
Is GetBaseDefinition
what you're after?
Basically
if (method.GetBaseDefinition() == method)
{
// Method was declared in this class
}
Here's an example showing the cases you're interested in:
using System;
using System.Reflection;
class Base
{
public virtual void Overridden() {}
public virtual void NotOverridden() {}
}
class Derived : Base
{
public override void Overridden() {}
public virtual void NewlyDeclared() {}
}
public class Test
{
static void Main()
{
foreach (MethodInfo method in typeof(Derived).GetMethods())
{
Console.WriteLine("{0}: {1} {2} {3}",
method.Name,
method == method.GetBaseDefinition(),
method.DeclaringType,
method.GetBaseDefinition().DeclaringType);
}
}
}
Output:
Overridden: False Derived Base
NewlyDeclared: True Derived Derived
NotOverridden: False Base Base
ToString: False System.Object System.Object
Equals: False System.Object System.Object
GetHashCode: False System.Object System.Object
GetType: True System.Object System.Object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With