In C#, arrays are data structures used to store multiple values of the same type. Arrays have a specific size and their elements are accessed through indices. Arrays are supported by the Array class in C# and each element must be of the same type.
The main characteristics of sequences are:
- They have a fixed size: Once defined, the size of the array cannot be changed.
- Zero-based indexing: The index of the first element in the array is 0.
- Homogeneous structure: All elements are of the same type.
Array Definition and Usage
1. Single-Dimensional Array
A single-dimensional array is a simple array where elements are stored in a linear sequence.
// Declare and initialize a single-dimensional array
int[] numbers = new int[5]; // An array with 5 elements
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
// Alternatively, you can initialize the array like this
int[] numbers = { 1, 2, 3, 4, 5 };
// Accessing elements
Console.WriteLine(numbers[0]); // Output: 1
Console.WriteLine(numbers[4]); // Output: 5
2. Multi-Dimensional Array
A multi-dimensional array (often called a matrix) is an array that has more than one dimension.
// Declare and initialize a 2D array (matrix)
int[,] matrix = new int[3, 3]; // A 3x3 matrix
matrix[0, 0] = 1;
matrix[0, 1] = 2;
matrix[0, 2] = 3;
matrix[1, 0] = 4;
matrix[1, 1] = 5;
matrix[1, 2] = 6;
matrix[2, 0] = 7;
matrix[2, 1] = 8;
matrix[2, 2] = 9;
// Alternatively, you can initialize the array like this
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
// Accessing elements
Console.WriteLine(matrix[0, 0]); // Output: 1
Console.WriteLine(matrix[2, 2]); // Output: 9
3. Jagged Array
A jagged array is an array of arrays, where each “inner” array can have different lengths.
// Declare and initialize a jagged array
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5] { 1, 2, 3, 4, 5 };
jaggedArray[1] = new int[3] { 6, 7, 8 };
jaggedArray[2] = new int[4] { 9, 10, 11, 12 };
// Accessing elements
Console.WriteLine(jaggedArray[0][1]); // Output: 2
Console.WriteLine(jaggedArray[2][3]); // Output: 12
4. Array of Strings
You can also have arrays of different types, like strings.
// Declare and initialize an array of strings
string[] fruits = new string[] { "Apple", "Banana", "Cherry" };
// Accessing elements
Console.WriteLine(fruits[0]); // Output: Apple
Console.WriteLine(fruits[2]); // Output: Cherry
5. Using Array Methods
C# arrays come with various useful methods.
// Declare and initialize an array
int[] numbers = { 1, 2, 3, 4, 5 };
// Get the length of the array
int length = numbers.Length; // Output: 5
// Sort the array
Array.Sort(numbers);
// Reverse the array
Array.Reverse(numbers);
// Finding an element
int index = Array.IndexOf(numbers, 3); // Output: 2
// Print sorted and reversed array
foreach (int number in numbers)
{
Console.WriteLine(number);
}