Lesson 07 of 30
Arrays and Collections
C# in Visual Studio 2026 — a hands-on guide for developers at every level.
Arrays
An array stores a fixed number of elements of the same type. The size is set at creation and cannot change.
// Declare and initialise
int[] scores = { 85, 92, 78, 96, 88 };
// Access by index (zero-based)
Console.WriteLine(scores[0]); // 85
Console.WriteLine(scores[^1]); // 88 (last element, C# 8+)
// Length
Console.WriteLine(scores.Length); // 5
Array Methods
Array.Sort(scores);
Array.Reverse(scores);
int idx = Array.IndexOf(scores, 92);
Console.WriteLine($"92 is at index {idx}");
Multi-Dimensional Arrays
// 2-D array (3 rows, 3 cols)
int[,] grid = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Console.WriteLine(grid[1, 2]); // 6
Ranges and Slices (C# 8+)
int[] nums = { 10, 20, 30, 40, 50 };
int[] slice = nums[1..4]; // { 20, 30, 40 }
int[] last2 = nums[^2..]; // { 40, 50 }
âšī¸ Array vs List
Use arrays when the size is fixed and performance is critical. Use List<T> (Lesson 8) when you need to add or remove elements dynamically.