ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IsSubclassOfRawGeneric

Is essentially a modified version of Type.IsSubClassOf that supports checking whether a class derives from a generic base-class without specifying the type parameters. For instance, it supports typeof(List<>) to see if a class derives from the List<T> class. The actual code was borrowed from http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class.

Source

/// <summary>
/// Alternative version of <see cref="Type.IsSubclassOf"/> that supports raw generic types (generic types without
/// any type parameters).
/// </summary>
/// <param name="baseType">The base type class for which the check is made.</param>
/// <param name="toCheck">To type to determine for whether it derives from <paramref name="baseType"/>.</param>
public static bool IsSubclassOfRawGeneric(this Type toCheck, Type baseType)
{
    while (toCheck != typeof(object))
    {
        Type cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
        if (baseType == cur)
        {
            return true;
        }

        toCheck = toCheck.BaseType;
    }

    return false;
}

Example

bool isDerived = someType.IsSubclassOfRawGeneric(typeof(List<>));

Author: Dennis Doomen

Submitted on: 17 feb. 2009

Language: C#

Type: System.Type

Views: 12526