Arrays

An array is a fixed-size, ordered collection of elements of the same type. Once created, its length cannot change.

Declaration & Initialization

// Declare and initialize
int[] numbers = { 1, 2, 3, 4, 5 };

// Declare with size, then assign
string[] names = new string[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";

// Shorthand
var scores = new int[] { 90, 85, 78, 92 };

Iterating Arrays

// for loop — use when you need the index
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine($"Index {i}: {numbers[i]}");
}

// foreach — cleaner when you just need values
foreach (int n in numbers)
{
    Console.WriteLine(n);
}

Multi-Dimensional Arrays

// 2D array (matrix)
int[,] matrix = {
    { 1, 2, 3 },
    { 4, 5, 6 }
};

Console.WriteLine(matrix[1, 2]); // 6
Console.WriteLine(matrix.GetLength(0)); // 2 rows
Console.WriteLine(matrix.GetLength(1)); // 3 cols

Jagged Arrays

A jagged array is an array of arrays, where each inner array can have a different length:

int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };
jagged[2] = new int[] { 6 };

Useful Array Methods

Array.Sort(numbers);
Array.Reverse(numbers);
int idx = Array.IndexOf(numbers, 3);
bool exists = numbers.Contains(5); // via LINQ