Tarik
Tarik

Reputation: 81721

How to get all the parent classes of a derived class in C# Reflection

It is weird that I was not able to find a similar question but this is what actually I want, finding all the parent classes of a derived class.

I tested a code with a hope that it works for me :

void WriteInterfaces()
{
    var derivedClass = new DerivedClass();
    var type = derivedClass.GetType();
    var interfaces = type.FindInterfaces((objectType, criteria) =>
                                            objectType.Name == criteria.ToString(),"BaseClass");

    foreach(var face in interfaces)
    {
        face.Name.Dump();
    }
}

interface BaseInterface
{}

class BaseClass : BaseInterface {}

class BaseClass2 : BaseClass {}

class DerivedClass : BaseClass2{}

Basically, here my main intention is to check if a derived class somehow inherits a base class somewhere in its base hierarchy.

However, this code returns null and works only with interfaces.

Upvotes: 0

Views: 1101

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

It sounds like you don't actually need all the other types - you just need Type.IsSubclassOf or Type.IsAssignableFrom. However, getting all the type in the hierarchy is easy using Type.BaseType:

public static IEnumerable<Type> GetClassHierarchy(Type type)
{
    while (type != null)
    {
        yield return type;
        type = type.BaseType;
    }
}

Upvotes: 7

Related Questions