Arrays and Lists
A C# array has a fixed size set at creation. foreach iterates over any collection — array or List<T> — without needing an index at all.
List<T>
List<T> is C#'s primary growable collection, from System.Collections.Generic — it manages its own resizing as you Add elements, and like every generic collection in C#, the <T> means it's type-safe: a List<int> can only ever hold ints.
Main.cs
Try it yourself →using System;
using System.Collections.Generic;
class Program {
static void Main() {
int[] numbers = { 4, 8, 15, 16, 23 };
int sum = 0;
foreach (int n in numbers) {
sum += n;
}
Console.WriteLine(sum);
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
Console.WriteLine(list.Count);
}
}Output
66 3
Next: strings — interpolation, and a genuine difference from Java: C#'s == compares string content, not references.
Practice exercise
Given int[] numbers = { 4, 8, 15, 16 }, sum all its elements with a foreach loop and print the total.