Arrays
Arrays are an essential data structure in C# that allow you to store multiple values of the same type in a single variable. They provide a convenient way to work with collections of data.
To declare an array in C#, you specify the type of the elements followed by square brackets []
and the name of the array. Here's an example:
1int[] numbers = new int[5];
In the above example, we declared an integer array named numbers
with a length of 5. To initialize the array, we used the new
keyword followed by the type and the desired length.
You can access elements in an array using their index. Array indices start at 0, so the first element is at index 0, the second element is at index 1, and so on. Here's an example:
1int[] numbers = { 1, 2, 3, 4, 5 };
2Console.WriteLine(numbers[0]); // Output: 1
In the above example, we initialized an integer array named numbers
with the values 1, 2, 3, 4, and 5. We then used the index 0
to access the first element in the array, which is 1
.
Arrays also provide properties and methods that allow you to manipulate and query their contents. Some commonly used properties and methods include:
Length
: Returns the number of elements in the array.Rank
: Returns the number of dimensions in the array.GetUpperBound
: Returns the highest index in a specified dimension of the array.Sort
: Sorts the elements in the array.
Here's an example of using the Length
property:
1int[] numbers = { 1, 2, 3, 4, 5 };
2Console.WriteLine(numbers.Length); // Output: 5
In the above example, we used the Length
property to get the number of elements in the numbers
array, which is 5
.
Arrays are a powerful tool for organizing and manipulating data in C#. They are commonly used in various algorithms and data structures.