Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsAssignableFrom in covariance and contravariance

How can I detect if type x is assignable from type y not only through inheritance hierarchy but also through covariance and contravariance?

like image 309
Alwyn Avatar asked Jul 12 '12 22:07

Alwyn


People also ask

What is difference between 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.

What is covariance and Contravariance in generics?

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.

What is covariant C#?

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.


1 Answers

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
like image 186
Thomas Levesque Avatar answered Sep 28 '22 15:09

Thomas Levesque