© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
25 replies
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);
    }
}
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Resizing an array
C#CC# / help
4y ago
✅ Issues with window resizing
C#CC# / help
13mo ago
WPF Forms is resizing 'something'?
C#CC# / help
4y ago
✅ array
C#CC# / help
4y ago