0

I have a method like

public IList<IList<int>> LevelOrderBottom(TreeNode root)
{   
   var result = new List<List<int>>();
   // ...
   return result;
}

and am getting compile-time error

Cannot implicitly convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.IList>'. An explicit conversion exists (are you missing a cast?)

I don't understand why that doesn't work, but

private static IList<int> ReturnAList()
{
    return new List<int>() { 1, 2, 3, };
}

does?

user7127000
  • 3,143
  • 6
  • 24
  • 41
  • And just today someone asked something very similar: https://stackoverflow.com/q/50526268/613130 (and I gave a possible answer) – xanatos May 25 '18 at 13:56
  • @TJWolschon No, quite different. `IList<>` is an interface of `List<>`, and `List<>` can be casted to `IList<>` without changing it (it is a reference) – xanatos May 25 '18 at 13:57
  • 2
    When you have `IList>`, you can add anything to it that implements `IList`. When you have `List>`, the only thing you can add to it is `List`. So if you have a reference R to `List>` where R is typed `IList>`, the static type checking will allow you to add things that the actual object doesn't. Casting a reference is for when the thing it refers to *actually is* the type you're casting to. In this case, it isn't. – 15ee8f99-57ff-4f92-890c-b56153 May 25 '18 at 13:59

0 Answers0