Suppose this works. Your client code is:
var result = List_2();
Since the contract allows adding to the result anything that's IList<int>
, you could possibly have
public class MyCustomIList : IList<int>
{
...
}
and then
var result = List_2();
result.Add( new MyCustomIList() );
But that's wrong!
Your result
is a list of List<int>
, you should not be allowed to add anything other than List<int>
or its derivatives there. However, you were able to add MyCustomIList
which is not related to the List<int>
.
If you need a broad picture of the issue, read more on covariance and contravariance.
The fundamental issue in this particular example comes from the Add
operation. If you don't need it, the IEnumerable
will do
static IEnumerable<IEnumerable<int>> List_2()
{
List<List<int>> parent = new List<List<int>>();
List<int> list = new List<int> { 1, 2, 3, 3, 4, 5 };
parent.Add(list);
return parent; // no error, this works
}
This has been covered already.
>` to `IList>`?
– SᴇM May 17 '19 at 05:56