0

I am trying to initialize a List<string> array and while I have looked at other resources trying them made my compiler throw errors all the time.

I have seen this question, but it did not help.

My code is:

List<string>[] list = new List<string>[3];
list[1].Add("text");

I get the error on the second line. I have tried:

List<string>[] list = new List<string>[3]();
List<string>[] list = new List<string>()[3];
List<string>[] list = new List<string>()
{
   new string("hh"),
   new string("gg")
};
List<string>[] list = new List<string>()
{
   "hh",
   "gg"
};

But none of these work.

Community
  • 1
  • 1
mathgenius
  • 503
  • 1
  • 6
  • 21
  • 1
    [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – germi Jul 07 '16 at 10:28
  • 1
    Do you want a list of strings or an array of lists of strings? – Charleh Jul 07 '16 at 10:29
  • List[] list = new List[3]; creates an array of 3 lists of string. If you just want data storage for string you can go with List list = new List(); and add values via list.Add("exampleStringValue"); – Paul Weiland Jul 07 '16 at 11:18
  • @Charleh, an array of lists of strings. x...'s answer is exactly what I was looking for. – mathgenius Jul 07 '16 at 11:32
  • @PaulWeiland, that is exactly what I do not want, but thanks, anyway! – mathgenius Jul 07 '16 at 11:33
  • @JonSkeet, I disagree that my question is a duplicate of that one, it certainly explains a lot about null exceptions (and well), but my problem was more along the lines of I didn't know how to properly initialize an array of List – mathgenius Jul 07 '16 at 11:34
  • 1
    It is a duplicate as is - if you'd asked "why is my array being initialized with null references" it wouldn't have been... but that question is basically useful for questions which show a lack of knowledge of what causes a NullReferenceException. – Jon Skeet Jul 07 '16 at 11:59

1 Answers1

2
  List<string>[] list = new List<string>[3];
  list[0] = new List<string>();
  list[1] = new List<string>();
  list[2] = new List<string>();
  list[1].Add("text");