C#C
C#2y ago
Tofaa

Array resizing issues

I'm so lost, i've been trying to resize my array

Here's the code
internal class SingleThreadObjectArray<T> : IObjectArray<T>
{
    private T[] array;
    private int max;

    internal SingleThreadObjectArray(int size)
    {
        array = new T[size];
        max = size;
    }

    public T? Get(int index)
    {
        return index < array.Length ? array[index] : default(T);
    }

    public void Set(int index, T? value)
    {
        if (index >= array.Length)
        {
            var newLength = index * 2 + 1;
            Array.Resize(ref array, newLength);
        }
        array[index] = value!;
        max = Math.Max(max, index);
    }

    public void Trim()
    {
        array.CopyTo(array, max + 1);
    }
}


However, whenever i try to set a higher index using Set, it throws an index out of bounds exception
Was this page helpful?