Brian Snow
Brian Snow

Reputation: 1143

Can't 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 haven't been able to find much on the subject of creating an array of List objects (actually only this thread), maybe because no search engines will search for brackets.

Is 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 just curious as to why the first line of code (the List[] example) doesn't work.

Upvotes: 5

Views: 3223

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564641

You can do this. The syntax would be:

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

Note that this only allocates an array of references - you'll need to actually construct the individual list elements before you use them:

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

Alternatively, you can use the collection initialization syntax (works well for small numbers of fixed elements), ie:

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

Upvotes: 7

Matthias
Matthias

Reputation: 16209

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

Upvotes: 3

xbrady
xbrady

Reputation: 1703

Try this:

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

You do the initialization of each list afterwards:

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

Upvotes: 6

Related Questions