Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Determine the classes that overridden a specific method

Suppose that I have this class :

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

and I have these classes that inherits from TestBase

Class A

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class TestA : TestBase
{
    public override bool TestMe() { return false; }
}

Class B

public class TestB : TestBase
{
    public override bool TestMe() { return true; }
}

Class C:

public class TestC : TestBase
{
    // this will not override the method
}

I would like to return only Class A and B because they override the Method TestMe() , How can I achieve that by creating a method in the Main class ?

  public List<string> GetClasses(object Method)
   {
     // return the list of classes A and B .
   }

>Solution :

Test for types that:

  1. Extends TestBase
  2. Declares a TestMe() method that’s:
    • Virtual
    • Non-abstract
var baseType = typeof(TestBase);

foreach(var type in baseType.Assembly.GetTypes())
{
    if(type.IsSubclassOf(baseType))
    {
        var testMethod = type.GetMethod("TestMe");
        if(null != testMethod && testMethod.DeclaringType == type && !testMethod.IsAbstract)
        {
            if(testMethod.IsVirtual)
            {
                // `type` overrides `TestBase.TestM()`
                Console.WriteLine(type.Name + " overrides TestMe()");
            }
            else
            {
                // `type` hides `TestBase.TestM()` behind a new implementation
                Console.WriteLine(type.Name + " hides TestMe()");
            }
        }
    }
}

Given that we search types returned by baseType.Assembly.GetTypes(), this only works for subclasses defined in the same assembly/project.

To search all loaded assemblies at runtime, use AppDomain.CurrentDomain to enumerate them all first:

foreach(var type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes()))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading