If the Covariant type parameters which added in .Net Framework 4 enable me to make assignments that look like polymorphism
Why I can write
IEnumerable<object> lst = new List<string>();
And I can't write
List<object> lst = new List<string>();
If the Covariant type parameters which added in .Net Framework 4 enable me to make assignments that look like polymorphism
Why I can write
IEnumerable<object> lst = new List<string>();
And I can't write
List<object> lst = new List<string>();
Because the List{T} type is invariant, thus in the second case it would be possible to do:
List<object> lst = new List<string>();
lst.Add(10);
This is invalid because you are adding an Int32 to a list of strings.
The IEnumerable{out T} type is covariant as implied by the 'out'. This means it is not possible to add items to it, only get items out of it, which makes the first statement valid.
This however is valid:
List<object> lst = new List<object>();
lst.AddRange(new string[] { "hello" });
There are 2 reasons why it doesn't work:
IEnumerable<T>
is covariant (it is declared public interface IEnumerable<out T>
), but IList<T>
isn't. Otherwise you would be able to do something like that:
IList<string> listOfStrings = ...
IList<object> listOfObjects = listOfStrings;
listOfObjects.Add(42); // would fail at runtime because it is actually a list of strings, not ints
Covariance and contravariance only work on interfaces, not on concrete classes
In the .NET Framework version 4, variant type parameters are restricted to generic interface and generic delegate types.