0

This is something I have been confused with for quite a while now. Not sure if it's a C# specific problem or some simple OOP fact I am not able to grasp.

IList<IList<int>> result = new List<IList<int>>(); //Works Fine
IList<IList<int>> result2 = new IList<IList<int>>();     //Gives Error because we cannot initialize interface
IList<IList<int>> result3 = new List<List<int>>();       //Gives Error please explain why
IList<IList<int>> result4 = new IList<List<int>>();      //Gives Error please explain why

For the above lines of code can someone please explain why line 3 and 4 are wrong and line 1 is right?

2 Answers2

3

Because in

R<S> = T<U>;
  • T : R. All your examples satisfy this. List : IList, List = List, and IList = IList.

  • T : new(). This disqualifies the Interfaces in 2 and 4.

  • U = S. The generic types must match, not be derivable. This disqualifies 3.

Since U = S, write it as this

R<S> = new T<S>;

then it's more clear. These four will satisfy the above requirements

IList<IList<int>> result = new List<IList<int>>();
List<IList<int>> result2 = new List<IList<int>>();   
IList<List<int>> result3 = new List<List<int>>(); 
List<List<int>> result4 = new List<List<int>>(); 
djv
  • 15,168
  • 7
  • 48
  • 72
-2

IList<int> and IList<IList<int>> aren't the same thing. You can't assign one to the other just like you can't assign a string to an int.

And the syntax is wack too. Every < needs an >, and vice-versa.

If you really want to do this you need

List<List<int>> result = new List<List<int>>();

Notice we are instantiating the concrete type, not the interface.

NotTheBatman
  • 132
  • 6
  • No I cannot do that because I sometimes get questions on Leetcode and the return type of expected response is: IList> – Anjani Kumar Agrawal Jan 31 '20 at 22:21
  • @AnjaniKumarAgrawal `List>` is an instance of `IList>` because List implements IList. You can't instantiate an `IList`, because it is an interface not a concrete type. `List` is the concrete implementation of `IList`. If its requiring an `IList` then `List` qualifies. Anything that implements `IList` would qualify. This is the foundational basis of Dependency Injection/Inversion of Control. Anything expecting an interface `IList` MUST accept any concrete implementation of `IList`. – NotTheBatman Feb 03 '20 at 16:10
  • 2
    `List is the concrete implementation of IList` No. `List` is *a* concrete implementation of `IList`. It is not *the* implementation. `This is the foundational basis of Dependency Injection/Inversion of Control.` I think you mean Object Oriented Programming. None of this has anything to do with DI/IoC. –  Feb 03 '20 at 18:57