Arrays

View saved

Create an array

Arrays have a fixed length after creation. Indexes start at zero.

int[] scores = { 88, 92, 76 };
Console.WriteLine(scores[0]);
Console.WriteLine(scores.Length);

Loop with for and foreach

foreach is ideal when you only need values.

foreach (int score in scores)
{
    Console.WriteLine(score);
}

Update an element

Assign through an index.

scores[2] = 80;
Console.WriteLine(scores[2]);

Array tips

  • Length is fixed; use lists when size changes
  • Out-of-range indexes throw exceptions
  • Multidimensional arrays exist but jagged arrays are common
  • Pass arrays to methods by reference to the array object

Comments

One comment per signed-in account. Comments are saved with this page’s URL.