Skip to content

Arrays

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.

int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = new string[3]; // length 3, all elements default to null
names[0] = "Alice";
names[1] = "Bob";
Console.WriteLine(numbers[0]); // 1
Console.WriteLine(numbers.Length); // 5
foreach (int n in numbers)
{
Console.WriteLine(n);
}
// Multi-dimensional array
int[,] 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 };

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 index
int index = 3;
if (index < numbers.Length)
{
Console.WriteLine(numbers[index]);
}
  1. Can you change the length of a C# array after it’s created?

    AnswerNo β€” array length is fixed at creation. Use List<T> if you need a resizable collection.
  2. What exception does accessing array[array.Length] throw?

    AnswerIndexOutOfRangeException β€” valid indices run from 0 to Length - 1.
  3. What’s the difference between a multi-dimensional array (int[,]) and a jagged array (int[][])?

    AnswerA 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.