Does My Type Subclass a Generic Type?

by Jim Mar 26, 2009 6:42 PM

It’s trivially easy to check if your type subclasses some other type with Type.IsSubclassOf(). But what if that subclass is a generic one? IsSubclassOf() doesn’t work for that.

Enter the IsSubclassOfGeneric() extension method. I’m pretty new to extension methods, and haven’t found a lot of practical uses for then yet, but I like this one. We’re using reflection and generics a lot in my current project and this has been nice in a couple of places…

/// <summary>
/// Check if a type subclasses a generic type
/// </summary>
/// <param name="genericType">The suspected base class</param>
/// <returns>True if this is indeed a subclass of the given generic type</returns>
public static bool IsSubclassOfGeneric(this Type type, Type genericType)
{
    Type baseType = type.BaseType;

    while (baseType != null)
    {
        if (baseType.IsGenericType && 
            baseType.GetGenericTypeDefinition() == genericType)
            return true;
        else
            baseType = baseType.BaseType;
    }
    return false;
}

Tags:

Add comment


(Shows Gravatar icon; will not be displayed)

  Country flag
Click to change captcha
biuquote
  • Comment
  • Preview
Loading