Array data type in C#
In C#, an array is a data structure that allows you to store and manipulate a fixed-size collection of elements of the same type. Arrays provide a way to store multiple values of the same data type in a contiguous block of memory. The elements in an array are accessed by their index, which starts from 0.
Here's an example that demonstrates the usage of arrays in C#:
// Declaring and initializing an array of integers
int[] numbers = { 1, 2, 3, 4, 5 };
// Accessing array elements by index
Console.WriteLine(numbers[0]); // Output: 1
Console.WriteLine(numbers[2]); // Output: 3
// Modifying array elements
numbers[3] = 10;
Console.WriteLine(numbers[3]); // Output: 10
// Getting the length of the array
int length = numbers.Length;
Console.WriteLine(length); // Output: 5
In the example above, we declare an array of integers named numbers and initialize it with some values using an array initializer. We can access individual elements of the array using square brackets ([]) and the zero-based index. The value of the array element at index 0 is 1, and the value at index 2 is 3. We can modify the value of an array element by assigning a new value to it.
The Length property of an array gives you the number of elements in the array. In this example, numbers.Length returns 5.
Arrays in C# have a fixed size, meaning you cannot change the number of elements once the array is created. However, you can resize an array using techniques like creating a new array with a different size and copying the elements from the old array to the new one.
C# supports multidimensional arrays as well as jagged arrays. Multidimensional arrays allow you to store elements in a rectangular grid, while jagged arrays are arrays of arrays, where each sub-array can have a different size.
Here's an example of a multidimensional array:
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Console.WriteLine(matrix[1, 2]); // Output: 6
In this example, we declare and initialize a 2D array named matrix with 3 rows and 3 columns. We can access individual elements using two indices, representing the row and column.
Arrays are commonly used in C# for storing collections of data, iterating over elements, and performing various operations on groups of values. They are fundamental data structures and are widely used in many programming scenarios.