0

I'm trying to create a collection of collections, like a 2D array. Each collection (inside the main collection) will be the same type, though. It's just that we don't know what those types are.

for example:

a collection that contains:
- a list of cats
- a list of houses
- a list of SO questions.

so a collection with 3x collections inside.

Now, I'm trying the following C# code and getting a compile time error when I'm trying to do this:

IList<Foo> foos1 = new List<Foo>(); // e.g. Cats.
List<Foo> foos2= new List<Foo>(); // e.g. Houses.

var fails = new List<IList>
{
   foos1 // Fails
};

var works = new List<IList>
{
   foos2 // Works
};

Can someone please explain why this is?

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • I don't understand your question. Why _should_ the `fails` example not fail? The list element type is `IList`. And `IList` does not implement/inherit `IList`. So you're trying to put an object of an incompatible type into the list. The whole point of generics is **so that exactly that scenario won't work**. Why do you need any sort of explanation for that? I can only surmise that your question really is why doesn't the generic `IList` not inherit `IList`. For that, see duplicate. – Peter Duniho Aug 22 '20 at 03:41
  • `IList` is covariant, `List` is not. It's a limitation of C# right now that they'll fix eventually. – Dai Aug 22 '20 at 03:42
  • @Dai - That's irrelevant to this question. – Enigmativity Aug 22 '20 at 03:43
  • 1
    @Enigmativity My mistake - I'll admit that I didn't read the question, I just glanced at the code and assumed that was the problem :) – Dai Aug 22 '20 at 03:45
  • @Dai - Yeah, that was my first thought. Then I realised that the OP was making lists of lists. – Enigmativity Aug 22 '20 at 03:47

1 Answers1

1

IList<T> implements the following interfaces: ICollection<T>, IEnumerable<T>, and IEnumerable.

List<T> implements the following interfaces IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, IReadOnlyList<T>, and IReadOnlyCollection<T>.

So an IList<T> cannot be cast to an IList, but a List<T> can.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172