Dominic Jonas
Dominic Jonas

Reputation: 5005

Check if class is a subclass of specific generic

I have the following classes:

public class HtSecurePage : UserControl, IDisposable
{

}

public class HtSecureInstancePage<T1> : HtSecurePage
{

}

public partial class NormalPage : HtSecurePage
{

}

public partial class InstancePage : HtSecureInstancePage<ZlsManager>
{

}

To check if NormalPage is a subClass of HtSecurePage I use the following pattern.

if (typeof(NormalPage).BaseType == typeof(HtSecurePage))
{

}

If I use this pattern against InstancePage, it is not working.

if (typeof(InstancePage).BaseType == typeof(HtSecureInstancePage<>))
{

}

I need to know if a Type is a direct subClass of HtSecurePage or HtSecureInstancePage<>. (It's important not to check against HtSecureInstancePage<ZlsManager>!) The Type T1 is unknown.

Upvotes: 1

Views: 80

Answers (2)

Adem Catamak
Adem Catamak

Reputation: 2009

Below function check your class' sub-class the same type supplied class. If types is generic, check operation is executed over generic type definition.

Method usage

bool isInherited = CheckIsDirectlyInherited(typeof(TestAbstract), new[] {typeof(SecondLevelAbstractClass), typeof(FirstLevelAbstract)});

Method

bool CheckIsDirectlyInherited(Type obj, Type[] baseTypes)
{
    if (obj.BaseType == null)
        return false;

    var objGenericDefinition = obj.BaseType;
    if (objGenericDefinition.IsGenericType)
    {
        objGenericDefinition = objGenericDefinition.GetGenericTypeDefinition();
    }

    foreach (Type baseType in baseTypes)
    {
        var baseTypeDefinition = baseType;
        if (baseTypeDefinition.IsGenericType)
            baseTypeDefinition = baseType.GetGenericTypeDefinition();

        if (objGenericDefinition == baseTypeDefinition)
            return true;
    }

    return false;
}

Upvotes: 2

AlbertK
AlbertK

Reputation: 13187

is a direct subClass of HtSecurePage

I think you already know how to do it

Console.WriteLine(typeof(HtSecureInstancePage<ZlsManager>).BaseType == typeof(HtSecurePage));

is a direct subClass of HtSecureInstancePage<>

To check it you can use something like this:

static bool IsDirectSubclassOfRawGeneric(Type parent, Type toCheck)
{
    return toCheck.BaseType.IsGenericType && parent == toCheck.BaseType.GetGenericTypeDefinition();
}
...
Console.WriteLine(IsDirectSubclassOfRawGeneric(typeof(HtSecureInstancePage<>), typeof(InstancePage)));

Upvotes: 1

Related Questions