Arrays
What it means
Section titled βWhat it meansβAn array in C# is a fixed-size collection of elements of the same type β once created, its length canβt change. Arrays are zero-indexed and are value types in terms of the container header, but the underlying storage is on the heap (arrays are reference types). For a resizable collection, use List<T> instead.
Examples
Section titled βExamplesβint[] numbers = { 1, 2, 3, 4, 5 };string[] names = new string[3]; // length 3, all elements default to nullnames[0] = "Alice";names[1] = "Bob";
Console.WriteLine(numbers[0]); // 1Console.WriteLine(numbers.Length); // 5
foreach (int n in numbers){ Console.WriteLine(n);}
// Multi-dimensional arrayint[,] grid = new int[3, 3];grid[0, 0] = 1;
// Jagged array (array of arrays, each row can have a different length)int[][] jagged = new int[2][];jagged[0] = new int[] { 1, 2, 3 };jagged[1] = new int[] { 4, 5 };Common mistake
Section titled βCommon mistakeβAccessing an array with an out-of-range index β C# doesnβt silently return null or undefined like some languages; it throws an IndexOutOfRangeException immediately.
int[] numbers = { 1, 2, 3 };Console.WriteLine(numbers[3]); // IndexOutOfRangeException -- valid indices are 0, 1, 2
// Always check against .Length before accessing a potentially out-of-range indexint index = 3;if (index < numbers.Length){ Console.WriteLine(numbers[index]);}Quick practice
Section titled βQuick practiceβ-
Can you change the length of a C# array after itβs created?
Answer
No β array length is fixed at creation. UseList<T>if you need a resizable collection. -
What exception does accessing
array[array.Length]throw?Answer
IndexOutOfRangeExceptionβ valid indices run from0toLength - 1. -
Whatβs the difference between a multi-dimensional array (
int[,]) and a jagged array (int[][])?Answer
A multi-dimensional array is a single rectangular block where every row has the same length; a jagged array is an array of separate arrays, each of which can have its own independent length.