Adding values to a C# array

Ross picture Ross · Oct 14, 2008 · Viewed 1.8M times · Source

Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:

int[] terms;

for(int runs = 0; runs < 400; runs++)
{
    terms[] = runs;
}

For those who have used PHP, here's what I'm trying to do in C#:

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}

Answer

Tamas Czinege picture Tamas Czinege · Oct 14, 2008

You can do this way -

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.

List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsList.Add(value);
}

// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();

Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).