- Array Definition
An array is a data structure that contains a fixed number of elements of the same type. Each individual item within an array is called an element. The number of dimensions an array has is known as its rank. The size of each dimension is its length, and the total number of elements across all dimensions is the array's length.
Note: Once an array is created, its size is fixed. C# does not have built-in support for dynamic arrays that can change size after instantiation.
- Array Classification
Arrays in C# are primarily classified into two types: one-dimensional and multidimensional.
- One-dimensional arrays: These can be visualized as a single list or vector of elements.
- Multidimensional arrays: These are arrays whose elements are themselves arrays. This creates a nested structure.
- Rectangular Arrays: A type of multidimensional array where every sub-array (or row) has the same length. Regardless of the number of dimensions, all elements are accessed using a single set of square brackets.
- Jagged Arrays: An array of arrays where each sub-array can be of a different length. Each dimension is accessed using its own pair of square brackets.
- Arrays as Objects
Every array instance is an object that inherits from the System.Array class. This means arrays have access to a variety of useful members defined in the Base Class Library (BCL).
Rank: A property that returns the number of dimensions in the array.Length: A property that returns the total number of elements in the array.
Arrays are reference types. This means a variable holding an array stores a reference to the array object, which resides on the managed heap. The array elements themselves can be either value types (e.g., int, bool) or reference types (e.g., objects, strings).
- Declaring Arrays
Declaring an array involves specifying its element type and its rank (number of dimensions). The rank is indicated by the number of commas within the square brackets.
Rule: The number of commas plus one equals the number of dimensions.
You cannot specify the length of the dimensions during declaration; the rank is part of the array's type, but the length is determined upon instantiation.
long[,,,] dataCube; // Declares a four-dimensional array of longs
- Instantiating Arrays
After declaration, you must create an instance of the array using the new keyword, specifying the length of each dimension.
// Instantiate a one-dimensional array of integers with a length of 4
int[] valuesList = new int[4];
// Instantiate a one-dimensional array of MyClass references with a length of 4
MyClass[] objectReferences = new MyClass[4];
// Instantiate a three-dimensional array of integers
// The total number of elements is 3 * 6 * 2 = 36
int[,,] coordinateGrid = new int[3, 6, 2];
- Accessnig Array Elements
Array elements are accessed using an index, which starts at 0 for each dimension. The index is placed inside square brackets immediately following the array name.
// Create a 5x10 two-dimensional array
int[,] matrix = new int[5, 10];
// Assign a value to an element
matrix[2, 3] = 42;
// Retrieve a value from an element
int retrievedValue = matrix[2, 3];
- Initialization
When an array is created, its elements are automatically initialized to their default values (e.g., 0 for numeric types, false for bool, null for reference types).
int[] scores = new int[4]; // All elements are initialized to 0
7.1. Explicit Initialization of One-Dimensional Arrays
For one-dimensional arrays, you can provide an initialization list enclosed in curly braces after the instantiation.
// The compiler infers the length from the number of initial values
int[] scores = new int[] { 95, 88, 76, 91 };
7.2. Explicit Initialization of Rectangular Arrays
Rectangular arrays are initialized using nested, comma-separated lists. Each dimension's initializer is enclosed in its own set of curly braces.
// A 3x2 two-dimensional array
int[,] grid = new int[,] { { 10, 1 }, { 2, 10 }, { 11, 9 } };
7.3. Initialization Syntax and Clarity
Proper use of commas, braces, and indentation is crucial for clarity when initializing multidimensional arrays.
- Use commas to separate elements and groups.
- Avoid commas immediately after an opening brace or before a closing brace.
- Use indentation to visually group elements by dimension.
- Read the rank specifier from left to right. The last number specifies the element, while the preceding numbers define the groupings.
// A 4x3x2 three-dimensional array
int[,,] cube = new int[4, 3, 2]
{
{ { 1, 2 }, { 3, 4 }, { 5, 6 } },
{ { 7, 8 }, { 9, 10 }, { 11, 12 } },
{ { 13, 14 }, { 15, 16 }, { 17, 18 } },
{ { 19, 20 }, { 21, 22 }, { 23, 24 } }
};
7.4. Shortcut Syntax
When declaring, instantiating, and initializing an array in a single statement, you can omit the new <type>[] part, providing only the initializer.
// Explicit
int[] numbers = new int[3] { 1, 2, 3 };
// Shortcut
int[] numbers = { 1, 2, 3 };
// Explicit
int[,] table = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
// Shortcut
int[,] table = { { 1, 2, 3 }, { 4, 5, 6 } };
7.5. Implicitly Typed Arrays
You can use the var keyword to let the compiler infer the array's type from the initializer, provided all elements are of a compatible type.
// Explicitly typed
int[] scores = new int[] { 10, 20, 30 };
// Implicitly typed
var scores = new[] { 10, 20, 30 };
// Explicitly typed
int[,] coordinates = new int[2, 2] { { 1, 2 }, { 3, 4 } };
// Implicitly typed
var coordinates = new[,] { { 1, 2 }, { 3, 4 } };
- Example
static void Main(string[] args)
{
// Create and initialize a 2x3 two-dimensional array
var coordinateGrid = new int[2, 3] { { 0, 1, 2 }, { 10, 11, 12 } };
Console.WriteLine($"Array Rank: {coordinateGrid.Rank}");
Console.WriteLine($"Dimension 0 Length: {coordinateGrid.GetLength(0)}");
// Iterate through the array using its dimensions
for (int i = 0; i < coordinateGrid.GetLength(0); i++)
{
for (int j = 0; j < coordinateGrid.GetLength(1); j++)
{
Console.WriteLine($"Element[{i}, {j}]: {coordinateGrid[i, j]}");
}
}
}