How To Detect If Type is Another Generic Type

Thanks very much for this post. I wanted to provide a version of Konrad Rudolph’s solution that has worked better for me. I had minor issues with that version, notably when testing if a Type is a nullable value type:

public static bool IsAssignableToGenericType(Type givenType, Type genericType)
{
    var interfaceTypes = givenType.GetInterfaces();

    foreach (var it in interfaceTypes)
    {
        if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType)
            return true;
    }

    if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
        return true;

    Type baseType = givenType.BaseType;
    if (baseType == null) return false;

    return IsAssignableToGenericType(baseType, genericType);
}

Leave a Comment