In C#, arrays provide a way to store and manipulate collections of items of the same data type. This tutorial will cover the basics of working with arrays in C#.
1. Declaring and Initializing Arrays:
You can declare an array by specifying its data type, followed by square brackets []
and the array name. Here's a simple example:
In this example, an integer array named numbers
is declared and initialized with values { 1, 2, 3, 4, 5 }
. The foreach
loop is used to iterate through the array and display its elements.
2. Accessing Array Elements:
You can access individual elements of an array using their index. Remember that array indices in C# start at 0. Here's an example:
In this example, the string array fruits
is initialized, and the element at index 2 ("Orange"
) is accessed and displayed.
3. Modifying Array Elements:
Arrays in C# are mutable, meaning you can change the values of their elements. Here's an example:
In this example, the value at index 2 of the numbers
array is modified from 30
to 35
.
4. Multi-Dimensional Arrays:
C# supports multi-dimensional arrays. The most common type is a 2D array. Here's an example:
This example initializes a 2D array named matrix
and displays its elements using nested loops.
5. Array Length and Methods:
Arrays in C# have a Length
property that indicates the number of elements in the array. Additionally, there are methods in the System.Array
class, such as Sort()
and IndexOf()
, which can be used for array manipulation.
Here's an example using the Length
property and the Sort()
method:
This example demonstrates sorting an array using Array.Sort()
and getting the array length.
6. Experiment:
- Create arrays of different data types.
- Explore other methods in the
System.Array
class. - Try working with multi-dimensional arrays.
Congratulations! You've learned the basics of working with arrays in C#. In the next tutorial, we'll explore functions and methods in C#.