IsAssignable Of covariance and contravariance

How to determine whether a type can be xassigned from a type ynot only through the inheritance hierarchy, but also through covariance and contravariance?

+5
source share
1 answer

IsAssignableFrom checks covariance and contravariance, you do not need anything:

// Covariance
typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<string>)).Dump(); // true
typeof(IEnumerable<string>).IsAssignableFrom(typeof(IEnumerable<object>)).Dump(); // false

// Contravariance
typeof(Action<string>).IsAssignableFrom(typeof(Action<object>)).Dump(); // true
typeof(Action<object>).IsAssignableFrom(typeof(Action<string>)).Dump(); // false
+8
source

All Articles