C# handles arrays much differently than C or C++ does. It treats them as an object for one thing, although they do have a fixed size. So I have some questions about arrays in C#:
-
If I create an array
new int[10]will the Length property be guaranteed to be 10 or does C# try and resize the array if I get close to filling it up? -
If I need to resize the array, do I have to create a new one with a larger size and then copy over each element in the array, or can I simply add more space without copying the elements over.
EDIT: it looks like you can use Array.Copy to copy the array over.
- The List collection in C# seems like a dynamically sized array (maybe a mix between arrays and linked lists). If I use a List instead of an array, can I control its size? (i.e. force it to be length 10, then set its size to 20 if I need more space)
It’ll be 10. Always 10.
You need to resize it and copy. There are some helper methods that make this easier, like
Array.Resize– but make no mistake that it is creating a new array and usingArray.Copyto put everything there. If you need a resizable collection, useList<T>.The size is controlled automatically. It will grow when needed. There is a constructor overload to accept the initial size. Internally, it also uses an array that is being resized when needed. When it’s filled; it grows by double of its current capacity, and copies everything in the new underlying array in the list. But all that magic happens behind the scenes. If you want to manually resize the internal array of the
List<T>, set theCapacityproperty to the number of items.