Unable to create an array of list objects

I have a line of code like this:

List<string>[] apples = new List<string>()[2];

Its purpose is simply to create an array of List objects. When I try to compile my code, the above line generates this error:

Cannot implicitly convert type 'string' to 'System.Collections.Generic.List []

I was not able to find a lot of information about creating an array of List objects (in fact, only this stream), perhaps because search engines will not search for brackets.

Is this the only way to create a collection of lists to put them in another list, like below?

List<List<string>> apples = new List<List<string>>(); //I've tried this and it works as expected

Thanks for any suggestions, I'm really curious why the first line of code (List [] example) does not work.

+5
source share
3

. :

List<string>[] apples = new List<string>[2];

, - , :

List<string>[] apples = new List<string>[2];
apples[0] = new List<string>();
apples[1] = new List<string>();

( ), :

List<string>[] apples = new[] { new List<string>(), new List<string>() };
+6

:

List<string>[] apples = new List<string>[2];

:

apples[0] = new List<string>();
+6
        var listArray = new List<string>[2];
        for (var i = 0; i < listArray.Length; i++)
        {
            listArray[i] = new List<string>();
        }
+3
source

All Articles