Skip to content
Codewilds

Lesson 13 of 34 · Arrays & Lists

C# Arrays and the foreach Loop

easy10 XP3 min read

Programs rarely work with one value at a time. A leaderboard has ten scores, a dungeon has dozens of rooms, a sentence has many words. An array stores a fixed number of values of the same type under one name, and the foreach loop lets you visit each of them without counting.

Creating arrays

int[] scores = new int[3];               // three ints, all 0
string[] heroes = { "Aria", "Bo", "Cy" }; // initializer
double[] prices = [9.99, 4.5, 12.0];     // collection expression (C# 12)

The type int[] means "array of int". An array's size is fixed when it is created. New arrays are filled with default values: 0 for numbers, false for bool, null for strings.

Indexing and Length

Elements are numbered from 0. The last index is therefore Length - 1:

string[] heroes = { "Aria", "Bo", "Cy" };
Console.WriteLine(heroes[0]);        // Aria
heroes[1] = "Bran";                  // replace an element
Console.WriteLine(heroes.Length);    // 3
Console.WriteLine(heroes[^1]);       // Cy — ^1 means "last"
string[] firstTwo = heroes[0..2];    // { "Aria", "Bran" } — a range, end excluded

Reading heroes[3] throws an IndexOutOfRangeException at runtime — the most common array bug.

Looping with for and foreach

Use for when you need the index:

for (int i = 0; i < heroes.Length; i++)
{
    Console.WriteLine($"{i + 1}. {heroes[i]}");
}

Use foreach when you only need the values. It is shorter and can never go out of bounds:

int[] damage = { 12, 7, 30 };
int total = 0;
foreach (int d in damage)
{
    total += d;
}
Console.WriteLine(total);   // 49

The loop variable of foreach is read-only: d = 0; inside the loop does not compile. To change elements, loop with an index: damage[i] = 0;.

Useful Array methods

int[] numbers = { 5, 2, 8, 1 };
Array.Sort(numbers);                       // numbers is now { 1, 2, 5, 8 }
Array.Reverse(numbers);                    // { 8, 5, 2, 1 }
int pos = Array.IndexOf(numbers, 5);       // 1 (or -1 if missing)
int[] copy = (int[])numbers.Clone();       // an independent copy

Arrays are references

An array variable does not hold the elements themselves — it holds a reference to them. Assigning an array to another variable copies the reference, not the data:

int[] a = { 1, 2, 3 };
int[] b = a;
b[0] = 99;
Console.WriteLine(a[0]);   // 99 — a and b are the same array

The same applies when you pass an array to a method: the method can change the caller's elements. If a method should not modify its input, build a new array for the result.

Common mistakes

  • for (int i = 0; i <= numbers.Length; i++) — the <= reads one element too far.
  • Using .Length() with parentheses or .Count — for arrays it is the property Length.
  • Expecting int[] b = a; to copy the array.

Assignment

Complete four methods in Program:

  1. Max(numbers) returns the largest number of a non-empty array (use foreach; do not sort).
  2. CountAbove(scores, threshold) returns how many scores are strictly greater than threshold.
  3. Average(values) returns the average of a double[], or 0 for an empty array.
  4. Reversed(numbers) returns a new array with the elements in reverse order and leaves numbers unchanged.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Arrays and lists in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+10 XP

Lesson 13 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.