Search code examples
c#allocation

How to create an uninitialized 2D array?


C# allows you to create an array without it being initialized with GC.AllocateUnitializedArray<T>. T can be any type, such as bool or int. However, I do not know of a way to do this to a 2D array, e.g. bool[,] or int[,].

I know that I could allocate a 1D array that is the size of the 2D array, and then access it like it was a 2D array, like this:

int[] array = GC.AllocateUninitializedArray<int>(width * height); //width and height are width and height of the array
// ... (array is initialized)
int arrayAccessExample = array[x * height + y]; //x and y are anything greater than 0 and less than width and height, respectively

But that's annoying to constantly do, and could easily lead to bugs if done wrongly. I could make the array access into a function, which would remove the potential for bugs, but that's still inconvenient and I'd rather just be able to use a real 2D array. Is there a way to allocate an uninitialized 2D array directly, or to "cast" a 1D array into a 2D array?


Solution

  • I would consider going down this path to make it easy for you:

    public class UnallocatedArray<T>
    {
        public UnallocatedArray(int width, int height)
        {
            array = GC.AllocateUninitializedArray<T>(width * height);
            this.Width = width;
            this.Height = height;
        }
        
        private int Width { get; init; }
        private int Height { get; init; }
        
        private T[] array = null;
    
        public T this[int x, int y]
        {
            get => array[x * this.Height + y];
            set => array[x * this.Height + y] = value;
        }
    }
    

    Then you'd be able to write:

    var ua = new UnallocatedArray<int>(4, 5);
    ua[2, 1] = 42;
    Console.WriteLine(ua[2, 1]);