Links
Variance allows to replace a type with a less-derived (covariance: derived → base) type or a more-derived type (contravariance: base → derived).
It is available for array types, delegate types, and generic types.
Assignment compatibility
Allow an object of a more derived type (derived) to be assigned to an object of a less derived type (base).
|
Derived derived;
Base base = derived;
|
Covariance
Allow a generic object of child class type (ex: string) to be assigned to a generic object of parent class type (ex: object).
 |
It works only with covariant interface |
|
var deriveds = new List<Derived>();
List<Base> bases = strings;
IList<Base> bases = strings;
var bases = (IList<Base>)deriveds;
IEnumerable<Base> bases = deriveds;
IReadOnlyList<Base> bases = deriveds;
IReadOnlyCollection<Base> bases = deriveds;
|
Create a covariant interface
|
var derivedVariants = new VariantList<Derived> { new Derived() };
IVariantList<Base> baseVariants = derivedVariants;
var derivedVariant = new Variant<Derived>();
IVariant<Base> baseVariant = derivedVariant;
interface IVariantList<out T> { }
class VariantList<T> : List<T>, IVariantList<T> { }
interface IVariant<out T> { }
class Variant<T> : IVariant<T> { }
|
Interface
|
Since
|
IEnumerable<out T> |
.NET Framework 4.0
|
IReadOnlyList<out T> |
.NET Framework 4.5
|
IReadOnlyCollection<out T> |
.NET Framework 4.5
|