Arrays & Lists

An array holds a fixed number of values of the same type, decided the moment it's created. A List<T> holds the same kind of values but can grow and shrink while your program runs. Most day-to-day code reaches for List<T>; arrays earn their place when the size genuinely never changes.

Arrays

You declare an array's element type followed by square brackets, then fill it with a comma-separated list in curly braces. Elements are accessed by a zero-based index — the first item is at position 0, not 1:

</> Program.cs
string[] fruits = { "apple", "banana", "cherry" };

Console.WriteLine(fruits[0]);
Console.WriteLine(fruits.Length);
fruits[1] = "blueberry";
Console.WriteLine(fruits[1]);
Output
apple
3
blueberry

You can change what's at an existing position (like swapping "banana" for "blueberry" above), but you can never add a fourth item to this array — its length of 3 is locked in at creation.

foreach

foreach walks through every element of a collection in order, without you having to manage an index variable yourself. It's the natural loop to reach for whenever you just need "do this for each item," and it works identically on arrays and lists:

</> Program.cs
int[] scores = { 88, 92, 79, 95 };

foreach (int score in scores)
{
    Console.WriteLine($"Score: {score}");
}
Output
Score: 88
Score: 92
Score: 79
Score: 95

List<T>

List<T> — pronounced "list of T," where T is whatever type you're storing, like List<string> or List<int> — is what most code actually uses instead of a raw array, because real programs rarely know their exact final size ahead of time. A shopping cart doesn't know how many items it'll hold when the page first loads:

</> Program.cs
List<string> cart = new List<string>();
cart.Add("Notebook");
cart.Add("Pen");
cart.Add("Eraser");

Console.WriteLine(cart.Count);
cart.Remove("Pen");

foreach (string item in cart)
{
    Console.WriteLine(item);
}
Output
3
Notebook
Eraser

Notice the property is called Count, not Length — arrays have Length, lists have Count. It's a small inconsistency you just have to remember.

Sorting a list

</> Program.cs
List<int> numbers = new List<int> { 5, 2, 9, 1 };
numbers.Sort();

foreach (int n in numbers)
{
    Console.Write(n + " ");
}
Output
1 2 5 9 
Note: List<T> lives in the System.Collections.Generic namespace. Projects created with dotnet new console today have implicit usings turned on, so it's already available without an explicit using line — but if you ever see a "type or namespace could not be found" error for List, that namespace is the fix.