Variance defines subtyping between more complex types. It may be either preserved, reversed, or ignored.
Covariance
Covariance allows implicit conversion for arrays, collection and generic types.
It allows a more specific type to be placed inside less parent type.
- String stringValue = “abc”;
- Object objValue = stringValue;
Now, see Covariance example:
- IEnumerable<string> stringValues = new List<string>();
- IEnumerable<object> objectValues =stringValues;
And, assignment compatibility is preserved.
ContraVariance
Contravariance allows implicit conversion for arrays, collection and generic types.
It allows less parent type to be implicitly placed inside more specific type.
Let, there is a method:
- static void SetMyObject(object obj) { }
- Action<object> myObject = SetMyObject;
- Ation<string> myString = myObject;
So, assignment compatibility is reversed.
Join the conversation! Your thoughts help the community grow.