Trying to build Array of Lists of Structs in C#. And getting a System.NullReferenceException with the best try (error on line test[i].Add(info1);
)
The question is not how to avoid System.NullReferenceException at all, but more like how to quickly build Array of Lists with predefined size of array, thus that one is able to use array[i].Add(Struct)
in it. If possible without looping all over the array, just to create the lists.
So these are the requirements:
- the size of the array should be predefined;
- the numbers of the lists per node should be arbitrary, and there should be a possibility that these are added easily;
- the structure should contain the
struct Info
.
This is the code, I have managed so far (copy and paste should work, to replicate the error):
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
List<Info>[] test = new List<Info>[entry];
for (int i = 0; i < 500 ; i+=3)
{
Info info1 = new Info()
{
capacity = i * 2,
name = i.ToString()
};
test[i].Add(info1);
}
for (int i = 0; i < 1000; i+=5)
{
Info info2 = new Info();
info2.capacity = i * 2;
info2.name = i.ToString() + i.ToString();
test[i].Add(info2);
}
}
struct Info
{
public int capacity;
public string name;
}
}