5

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.

4
  • 3
    Simple mistake, remove the parentheses. Commented Feb 10, 2012 at 0:17
  • Thanks, I can't believe I didn't think to try that. Commented Feb 10, 2012 at 0:19
  • Make it interesting, ask why the error message is so lousy. Commented Feb 10, 2012 at 0:28
  • Haha, actually I was trying to go through the error message logically in my head before I posted this question....It didn't make a whole lot of sense to me, but I figured it was because I'm a newbie. Though I think if I asked why it's such a lousy error message, no one would have the answer :) Commented Feb 10, 2012 at 0:37

3 Answers 3

7

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>() };
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I didn't know about the 'collection initialization syntax,' I can see how that would be useful.
6

Try this:

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

You do the initialization of each list afterwards:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.