Arrays (1D, 2D Multidimensional & Jagged) Masterclass
Welcome to Phase 5 (Chapter 12): C# Arrays (1D, 2D Multidimensional & Jagged) Masterclass! An array is a fixed-size collection of elements of the same data type stored in contiguous memory locations. In this chapter, we explore 1D single-dimensional arrays, 2D rectangular multidimensional arrays ([,]), arrays of arrays (jagged arrays [][]), array traversal, sorting, searching, copying, passing arrays to methods, and understanding array limitations.
Array elements are zero-indexed, starting from index 0 up to Length - 1. In C# 8+, you can also use the index-from-end operator ^1 to access the last element directly.
// Array declaration and initialization
int[] marks = { 85, 90, 78, 92, 65 };
Console.WriteLine($"Array Length: {marks.Length}");
// Traversing using foreach
foreach (int mark in marks)
{
Console.WriteLine($"Mark: {mark}");
}
// Array Static Methods: Sort, Reverse, BinarySearch
Array.Sort(marks); // Sorts array in ascending order
Console.WriteLine($"Sorted Min: {marks[0]}, Max: {marks[^1]}"); // ^1 is index from end in C# 8+
int index = Array.BinarySearch(marks, 90);
Console.WriteLine($"Index of 90: {index}");
C# provides two distinct types of multi-dimensional arrays:
// 1. Multidimensional 2D Rectangular Array [rows, cols]
int[,] matrix = {
{ 10, 20, 30 },
{ 40, 50, 60 }
};
Console.WriteLine($"Matrix element [1, 2]: {matrix[1, 2]}"); // 60
// 2. Jagged Array (Array of arrays with variable row lengths)
int[][] jagged = new int[2][];
jagged[0] = new int[] { 1, 2, 3 };
jagged[1] = new int[] { 4, 5 };
Console.WriteLine($"Jagged element [1][0]: {jagged[1][0]}"); // 4
Arrays are reference types. When you pass an array to a method, the method receives a pointer reference to the original heap array, allowing changes to elements to persist:
static void DoubleElements(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
arr[i] *= 2;
}
int[] nums = { 1, 2, 3 };
DoubleElements(nums);
Console.WriteLine($"Doubled elements: {string.Join(", ", nums)}"); // 2, 4, 6
Q1: What is the main difference between int[,] and int[][]?
int[,] is a single rectangular block of contiguous memory where every row has the same number of columns. int[][] is an array of separate array references, allowing rows of varying lengths.
Q2: Can arrays be resized in C#?
No. Arrays are fixed in size once instantiated. Array.Resize() actually allocates a brand new array under the hood and copies elements over.