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#?
Asked
Active
Viewed 142 times
2 Answers
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 – 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
-
2Maybe, but this actually allocates a new array; that should be made clear in your answer. – Johnathan Barclay Jan 28 '20 at 16:48
-
-
1@DStanley No, where did I imply that I did? Someone may see this and think an existing array is being resized; it isn't. I'm not suggesting it won't be satisfactory for the OP. – Johnathan Barclay Jan 28 '20 at 16:54