How can I detect if type x
is assignable from type y
not only through inheritance hierarchy but also through covariance and contravariance?
In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.
Covariance and contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.
Covariance in C# is a concept of preserving assignment compatibility. It allows us to assign an object, variable, or parameter of a more derived type to an object, variable, or parameter of a less derived type.
IsAssignableFrom
does check covariance and contravariance, you don't need anything else:
// 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With