How to check if `IEnumerable<T1>` covariant to `IEnumerable<T2>`?

In your specific case it does not work because value types do not support co-variance.

But for the question how to determine if an IEnumerable<T2> is co-variant to IEnumerable<T1>:

The method Type.IsAssignableFrom() tells you if an instance of a certain type is assignable to a variable of this type. So you can implement your method like that:

public static bool IsCovariantIEnumerable(Type T1, Type T2)
{
    Type enumerable1 = typeof(IEnumerable<>).MakeGenericType(T1);
    Type enumerable2 = typeof(IEnumerable<>).MakeGenericType(T2);
    return enumerable1.IsAssignableFrom(enumerable2);
}

Usage:

if (IsCovariantIEnumerable(typeof(object), typeof(string))
    Console.WriteLine("IEnumerable<string> can be assigned to IEnumerable<object>");

But IsCovariantIEnumerable(typeof(object), typeof(MyStruct)) will return false for the reason stated above.


For completeness: Of course you don't need an extra method as you can easily do typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<string>).


Value types do not support covariance as it would change their internal representation [1].

If you want to avoid weird cases i would recommend using IsAssignableFrom instead:

public static bool IsCovariantIEnumerable(Type T1, Type T2) => T1.IsAssignableFrom(T2);