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;
}
Best Answer


You can do this way -

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

Optionally you can use lists - the advantage of lists is that 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 are a bit more than 2 times cheaper than foreach loops on List, b) Looping on array is around 2 times cheaper than looping on List, c) looping on array using for is 5 times cheaper than looping on List using foreach (which most of us do).</p>