Jujek
Jujek

Reputation: 45

Initializing jagged arrays with Lists<int> inside by a for loop

I get NullReferenceException when I want to add item to my elements in jagged array.

public List<int>[][] Map;

void Start()
{
    Map = new List<int>[60][];
    for(byte x = 0; x < 60 ; x++)
    {
        Map[x] = new List<int>[60];
        // initialization of rows
    }

    Map [23] [34].Add (21);
}

Upvotes: 2

Views: 638

Answers (1)

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

You have a jagged array which each of its elements is a List<int>. You initialize the array but not the elements.

So when you call Add on an uninitialized element which is a List<int> you get the exception.

Map = new List<int>[60][];
for (int x = 0; x < 60; x++)
{
    Map[x] = new List<int>[60];

    for (int y = 0; y < 60; y++)
    {
        Map[x][y] = new List<int>(); // initializing elements
    }
    // initialization of rows
}

Map[23][34].Add(21);

Upvotes: 2

Related Questions