Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a type is assignable to an open generic type when closed with same type parameters?

I need a method that returns true if the passed type is assignable to (derives from) the closure of an open (unbounded) generic type. The method should work as follows:

OpenGenericIsAssignableFrom(typeof(ICollection<>), typeof(IList<String>))

Should return true.

like image 777
silasdavis Avatar asked Nov 28 '25 08:11

silasdavis


1 Answers

Why not simply close the open generic type and see if that is assingable from the closed type? The catch would be that closing it with the same arguments might not be valid so you'd need to catch that

private static bool OpenGenericIsAssignableFrom(
    Type openGenericType, 
    Type typeToCheck)
{
    if (!openGenericType.IsGenericType || typeToCheck == null) return false;

    if(typeToCheck.IsGenericType)
    {
        var typeArgs = typeToCheck.GetGenericArguments();
        if (typeArgs.Length == openGenericType.GetGenericArguments().Length)
        {
            try
            {
              var closed = openGenericType.MakeGenericType(typeArgs);
              return closed.IsAssignableFrom(typeToCheck);
            }
            catch
            {
              //violated type contraints
              return false
            }
        }
    }
    else 
    {
        return OpenGenericIsAssignableFrom(openGenericType, typeToCheck.BaseType) 
              || typeToCheck.GetInterfaces()
                    .Any(i=> OpenGenericIsAssignableFrom(openGenericType,i));
    }
}
like image 179
Rune FS Avatar answered Nov 30 '25 20:11

Rune FS