-2

I want an array capacity to increase as I add items in order to add as many items to it as possible. Is there a way to do this in C#?

smeel
  • 29
  • 2

2 Answers2

7

In C#, arrays are fixed lenght. The only way would be to create a new array, copy the contents and add the data.

Or just use List<T> or any other self-growing collection instead. They deal with exactly that part of the plumbing.

Christopher
  • 9,634
  • 2
  • 17
  • 31
  • Couldn't hey us an ArrayList as well? That way they could consistently change the capacity of the collection? – olminkow Jan 28 '20 at 17:03
  • 1
    @RookTKO Yes and No. ArrayList is the pre-generics List. All that pre-generic stuff should be quietly burried and forgotten. If you want to get rid of type safety, you can always use `List` https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist#remarks – Christopher Jan 28 '20 at 18:48
1

Is this what you're after?

Array.Resize(ref YourArray, i + 1);
Ryan Thomas
  • 1,724
  • 2
  • 14
  • 27