Arrays

An array is a fixed-size, zero-based sequence of elements of one type, allocated on the heap.

Concept

An array is a fixed-size, zero-based sequence of elements of one type, allocated on the heap. Elements get default values (0, false, null) unless initialized.

Length gives the size; indexes run from 0 to Length - 1.

Index from end: ecus[^1] is the last element. Ranges: ecus[1..3] copies elements 1 and 2.

Accessing outside the bounds throws IndexOutOfRangeException — C# never reads random memory.

Multidimensional and Jagged Arrays Rectangular (multidimensional): int[,] grid = new int[2, 3]; — one block, accessed as grid[row, col]; Rank and GetLength(dim) describe it.

Jagged: int[][] jagged — an array of arrays whose rows can differ in length.

Assigning an array copies the reference. Use Clone(), Array.Copy, CopyTo or a range to copy elements (shallow copy: reference-type elements are shared).

The Array Class Array.Sort, Array.Reverse, Array.IndexOf, Array.BinarySearch (on sorted arrays), Array.Find, Array.Exists, Array.Resize (allocates a new array), Array.Fill, Array.Clear.

int[] numbers = { 10, 20, 30 };
double[] readings = new double[4];
string[] ecus = ["VCU", "BMS"];   // collection expression (C# 12)

Why It Matters

Arrays are the fastest, most compact collection: CAN payloads (byte[]), sample buffers, lookup tables and matrix data all use them, and every other collection is built on top of arrays.

Syntax

T[] a = new T[n];
T[] b = { x, y, z };
T[,] m = new T[rows, cols];
T[][] j = new T[rows][];
var last = a[^1]; var part = a[1..3];

Example

// One-dimensional arrays: fixed length, zero-based
int[] numbers = { 10, 20, 30 };
double[] readings = new double[4];            // default values: 0
string[] ecus = ["VCU", "BMS", "ABS", "EPS"]; // collection expression (C# 12)
Console.WriteLine($"numbers: {string.Join(", ", numbers)} (Length {numbers.Length}), readings[2] = {readings[2]}");
Console.WriteLine($"first ecu {ecus[0]}, last ecu {ecus[^1]}, slice [1..3] = {string.Join("/", ecus[1..3])}");

// Multidimensional (rectangular) array
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine($"grid rank {grid.Rank}, rows {grid.GetLength(0)}, cols {grid.GetLength(1)}, grid[1,2] = {grid[1, 2]}");

// Jagged array: an array of arrays with different lengths
int[][] jagged = [[1], [2, 3], [4, 5, 6]];
foreach (int[] row in jagged) Console.Write($"[{string.Join(",", row)}] ");
Console.WriteLine();

// Copying: assignment copies the reference; Clone / CopyTo copy the elements
int[] alias = numbers;
int[] copy = (int[])numbers.Clone();
alias[0] = 99;
Console.WriteLine($"after alias[0] = 99: numbers[0] = {numbers[0]}, copy[0] = {copy[0]}");

// Searching and sorting with the Array class
int[] data = [42, 7, 19, 3, 25];
Console.Wr
…

Expected Result

numbers: 10, 20, 30 (Length 3), readings[2] = 0
first ecu VCU, last ecu EPS, slice [1..3] = BMS/ABS
grid rank 2, rows 2, cols 3, grid[1,2] = 6
[1] [2,3] [4,5,6] 
after alias[0] = 99: numbers[0] = 99, copy[0] = 10
IndexOf(19) = 2, Exists(>40) = True, Find(<10) = 7
sorted: 3 7 19 25 42, BinarySearch(25) = 3
reversed: 42 25 19 7 3
resized to 7: 42 25 19 7 3 0 0
IndexOutOfRangeException: Index was outside the bounds of the array.

Common Mistakes

Off-by-one: using <= with Length in a loop, or a[a.Length].

Believing int[] b = a; makes a copy (see alias above).

Calling BinarySearch on an unsorted array.

Expecting Array.Resize to keep the same array object — it creates a new one.

Using arrays when the size changes often — use List<T>.

Best Practices

Use arrays for fixed-size data and interop; List<T> for growing data.

Return IReadOnlyList<T> (or copies) instead of exposing internal arrays.

Prefer foreach, ranges and Span<T> (Module 41) over manual index arithmetic.

Use Array.Empty<T>() or [] instead of new T[0].

Interview Relevance

High: "array vs List<T>", "rectangular vs jagged", array algorithm problems (reverse, rotate, find duplicates, two-sum, maximum subarray).

Practice Questions

Find the minimum, maximum and average of an array without LINQ.

Rotate an array right by k positions.

Transpose a 3×3 rectangular array.

Remove duplicates from a sorted array in place.

Merge two sorted arrays into one sorted array.

Quick Quiz

Q1. (Predict the output) int[] a = {1, 2, 3}; int[] b = a; b[0] = 9; Console.WriteLine(a[0]);

Answer: 9 — both variables reference the same array (verified).

Q2. (Multiple choice) What does arr[^1] return? A) The first element B) The last element C) An exception D) The length Answer: B.

Q3. (True/False) A jagged array's rows must all have the same length.

Answer: False. That describes a rectangular array.

Q4. (Find the bug) for (int i = 0; i <= a.Length; i++) sum += a[i];

Answer: <= reads a[a.Length] and throws IndexOutOfRangeException; use <.

Coding Challenge

Write int[] MovingAverage(int[] samples, int window) returning the integer average of each full window (e.g. [2,4,6,8], window 2 → [3,5,7]).

static int[] MovingAverage(int[] samples, int window)
{
    var result = new int[samples.Length - window + 1];
    int sum = 0;
    for (int i = 0; i < samples.Length; i++)
    {
        sum += samples[i];
        if (i >= window) sum -= samples[i - window];
        if (i >= window - 1) result[i - window + 1] = sum / window;
    }
    return result;
}
Console.WriteLine(string.Join(",", MovingAverage([2, 4, 6, 8], 2)));