Arrays in C#
Arrays in C# are used to store collections of elements of the same data type. C# supports single-dimensional arrays, multidimensional arrays, and jagged arrays.
1. Single-Dimensional Array:
A single-dimensional array is a collection of elements stored in a linear sequence. It is declared with a specified data type, followed by square brackets []
:
int[] numbers = new int[5]; // Declare an integer array of size 5
2. Multidimensional Array:
A multidimensional array is an array of arrays. Commonly used are two-dimensional arrays, but you can have arrays with more dimensions.
Two-Dimensional Array:
Three-Dimensional Array:
3. Jagged Array:
A jagged array is an array of arrays where each element can be an array of different sizes.
int[][] jaggedArray = new int[3][];
Jagged arrays are flexible and allow different lengths for each row.
Arrays in C# are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. Array elements are accessed using square brackets []
.