C# Multi-dimensional arrays
In C#, multi-dimensional arrays allow you to store data in more than one dimension. They are useful for representing tables or matrices where data is organized into rows and columns.
Types of Multi-Dimensional Arrays
- Two-Dimensional Arrays: Often used to represent a matrix or table of data.
- Three-Dimensional Arrays: Used to represent data in a 3D space (e.g., layers of a table).
- N-Dimensional Arrays: You can create arrays with even more dimensions, but it is uncommon to go beyond 3D.
1. Two-Dimensional Arrays
A two-dimensional array is like a table, with rows and columns.
Declaring a Two-Dimensional Array
dataType
specifies the type of elements the array will store.- The
[,]
indicates that it's a two-dimensional array.
Initializing a Two-Dimensional Array
You can also initialize it with values at the time of declaration:
Accessing Elements in a Two-Dimensional Array
Elements are accessed using two indices, one for the row and one for the column:
Modifying Elements
You can also modify elements using their indices:
Example of Two-Dimensional Array
2. Three-Dimensional Arrays
A three-dimensional array adds another layer, which can be visualized as multiple 2D tables stacked on top of each other.
Declaring a Three-Dimensional Array
For example:
Accessing and Modifying Elements
You can access or modify elements using three indices:
3. Higher-Dimensional Arrays
C# also supports higher-dimensional arrays (4D, 5D, etc.), though they are rarely used. They follow the same basic principles, but their usage becomes more complex.
Multi-Dimensional Array Properties and Methods
Length: Returns the total number of elements across all dimensions.
GetLength(dimensionIndex): Returns the number of elements in a specific dimension.
Example of a Three-Dimensional Array
Summary
- Multi-dimensional arrays store data in more than one dimension (2D, 3D, etc.).
- Elements are accessed using multiple indices (one for each dimension).
- You can declare, initialize, access, and modify multi-dimensional arrays just like single-dimensional arrays, but with multiple indices.
- Two-dimensional arrays are the most common, often used to represent matrices or tables.