2D Array with burst - is the following a valid approach or will that cause trouble down the road?

I’m experimenting around and don’t really completely understand everything yet so I’d appreciate if someone more knowledgeable could tell me if the following approach is safe&sane:

public struct Fast2DArray<T> : System.IDisposable where T: struct
{
    private int sizeX;
    private NativeArray<T> flatArray;


    public Fast2DArray(int sizeX, int sizeY, Allocator allocator)
    {
        this.sizeX = sizeX;
        flatArray = new NativeArray<T>(sizeX * sizeY, allocator);
    }

    public T this[int x, int y]
    {
        get { return flatArray[x + y * sizeX]; }
        set { flatArray[x + y * sizeX] = value; }
    }

    public void Dispose()
    {
        flatArray.Dispose();
    }
}

It seems to work and is very quick from what I benchmarked, but I might be missing something so I feel rather insecure about it.

1 Like

Looks good, just make sure to add some boundary checks in case x + y * sizeX is smaller than 0 or bigger than array’s max length

1 Like