Array of an unknown length in C#
I've just started learning C# and in the introduction to arrays they showed how to establish a variable as an array but is seems that one must specify the length of the array at assignment, so what if I don't know the length of the array?
Solution 1:
Arrays must be assigned a length. To allow for any number of elements, use the List
class.
For example:
List<int> myInts = new List<int>();
myInts.Add(5);
myInts.Add(10);
myInts.Add(11);
myInts.Count // = 3
Solution 2:
Use List<>
to build up an 'array' of unknown length.
Use List<>.ToArray()
to return a real array, and not a List
.
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
var array = list.ToArray();
Solution 3:
A little background information:
As said, if you want to have a dynamic collection of things, use a List<T>
. Internally, a List uses an array for storage too. That array has a fixed size just like any other array. Once an array is declared as having a size, it doesn't change. When you add an item to a List
, it's added to the array. Initially, the List
starts out with an array that I believe has a length of 16. When you try to add the 17th item to the List
, what happens is that a new array is allocated, that's (I think) twice the size of the old one, so 32 items. Then the content of the old array is copied into the new array. So while a List
may appear dynamic to the outside observer, internally it has to comply to the rules as well.
And as you might have guessed, the copying and allocation of the arrays isn't free so one should aim to have as few of those as possible and to do that you can specify (in the constructor of List
) an initial size of the array, which in a perfect scenario is just big enough to hold everything you want. However, this is micro-optimization and it's unlikely it will ever matter to you, but it's always nice to know what you're actually doing.
Solution 4:
You can create an array with the size set to a variable, i.e.
int size = 50;
string[] words = new string[size]; // contains 50 strings
However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List
.
Solution 5:
Use an ArrayList
if in .NET 1.x, or a List<yourtype>
if in .NET 2.0 or 3.x.
Search for them in System.Collections
and System.Collections.Generics
.