Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Say I have a base class TestBase where I define a virtual method TestMe()

class TestBase {     public virtual bool TestMe() {  } } 

Now I inherit this class:

class Test1 : TestBase {     public override bool TestMe() {} } 

Now, using Reflection, I need to find if the method TestMe has been overriden in child class - is it possible?

What I need it for - I am writing a designer visualizer for type "object" to show the whole hierarchy of inheritance and also show which virtual methods were overridden at which level.

like image 594
Andrey Avatar asked May 28 '10 20:05

Andrey


People also ask

How do we identify if a method is an overridden method?

When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the way by which java achieve Run Time Polymorphism.

What is invoke method c#?

This method dynamically invokes the method reflected by this instance on obj , and passes along the specified parameters. If the method is static, the obj parameter is ignored. For non-static methods, obj should be an instance of a class that inherits or declares the method and must be the same type as this class.

Can we override already overridden method?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.


2 Answers

Given the type Test1, you can determine whether it has its own implementation declaration of TestMe:

typeof(Test1).GetMethod("TestMe").DeclaringType == typeof(Test1) 

If the declaration came from a base type, this will evaluate false.

Note that since this is testing declaration, not true implementation, this will return true if Test1 is also abstract and TestMe is abstract, since Test1 would have its own declaration. If you want to exclude that case, add && !GetMethod("TestMe").IsAbstract

like image 177
Rex M Avatar answered Oct 16 '22 18:10

Rex M


I was unable to get Ken Beckett's proposed solution to work. Here's what I settled on:

    public static bool IsOverride(MethodInfo m) {         return m.GetBaseDefinition().DeclaringType != m.DeclaringType;     } 

There are tests in the gist.

like image 36
ESV Avatar answered Oct 16 '22 17:10

ESV