Storing a fixed set of values in an array
An array is the simplest way to keep several values together. It has a fixed length chosen when you create it.
Creating and reading an array
C#
string[] days = new string[3];
days[0] = "Monday";
days[1] = "Tuesday";
days[2] = "Wednesday";
for (int i = 0; i < days.Length; i++)
{
outputLabel.Text += days[i] + "<br>";
}Two things to remember
- Numbering starts at zero, so a three item array runs from index zero to index two.
- Asking for an index outside the range throws an exception, which is the most common array mistake.
When to use one. Choose an array when the count is fixed and known. When the count can grow or shrink, use a list instead.
For looking values up by a name rather than a position, see the dictionary lesson.