Trying to make a sparse 2D list,. argumentOutOfRangeException

I have made a 2D list which i want to use sparsely. That is, the first layer will mostly be packed efficiently, but the second one will not.

The very first thing i’m attempting to do is set element [0][4]

and this throws an argumentOutOfRangeException

Here’s how i’m declaring the list:

List<List<Reverberation>> reverberations = new List<List<Reverberation>>(); //Creates new nested List

And here’s where i’m attempting to set it. The passed in value of chunkIndex is 4 in this case:

public int StartReverberation(FracturedChunk origin, int chunkIndex, Vector3 originPos)
        print("Starting reverb: " + chunkIndex);
        int index = nextReverb;
        reverberations[index][chunkIndex] = new Reverberation(origin);
        Reverberation temp = reverberations[index][chunkIndex];
        temp.processed = true;
        reverbOrigins[index] = originPos;

        return index;

How do i accomplish what i’m trying to do? x

This line alone:

List<List<Reverberation>> reverberations = new List<List<Reverberation>>();

doesn’t add any elements to the lists so accessing them like that will throw that exception. You would have to fill it with elements to be able to get/set them by index. I used an array with null values, but you could probably do something similar with lists:

Reverberation[][] reverberations;

void InitArray()
    reverberations = new Reverberation[5][];
    for(int i=0; i<reverberations.Length; i++)
        reverberations *= new Reverberation[5];*

Without the for loop it will be an array of 5 uninitialized arrays so you would not be able to set/get any values from them. This way you should be able to check reverberations[x][y] to be null or not and set it the same way you have written already.
I don’t know exactly what you want but it will be more complex to expand/shrink the arrays vs lists, and you need to make sure you don’t go outside the array’s length (the size must be predetermined). With lists I don’t know if you can have null values but I’m not sure if it’s problematic for you to have it full of instances of the Reverberation class. Perhaps check out hashtables, they can have random values set or nulled out by setting indexes directly like you’re doing.