IsSubclassOfRawGeneric

        /// <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<>));

Description

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.

Details

Double click on the code to select all.

 

;