Why isn't List<List<int>> implictly converted to IList<IList<int>?

Viewed 43

Why can a List<List<int> not be passed to a function which accepts an IList<IList<int>?

I can see how this type conversion may be hard to infer. However, it seems to work fine when converting to an IEnumerable<IEnumerable<int> or starting with a int[][], as you can see from my test program. I can't understand why some of these type conversions are infered, when others are not.

 internal class Program
    {
        static void Main(string[] args)
        {
            int[][] jaggedArray = { new int[]  { 0 } };
            Console.WriteLine(AcceptsIEnumerable(jaggedArray));
            Console.WriteLine(AcceptsIList(jaggedArray));

            List<List<int>> listArray = new() { new List<int> { 0 } };
            Console.WriteLine(AcceptsIEnumerable(listArray));
            // Not valid! Why?
            //Console.WriteLine(AcceptsIList(listArray));
        }

        static bool AcceptsIEnumerable(IEnumerable<IEnumerable<int>> x)
        {
            return true;
        }
        static bool AcceptsIList(IList<IList<int>> x)
        {
            return true;
        }

    }
0 Answers
Related