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
- Author: Dennis Doomen
- Submitted on: 2/17/2009 10:05:31 AM
- Language: C#
- Type: System.Type
- Views: 4330
Double click on the code to select all.