C# Arrays
An array is a collection of variables of the same type, stored in a contiguous block of memory. In C#, an array can be of any type, including basic types (such as int, float, and char), reference types (such as strings and objects), and user-defined types (such as structures and classes).
Declaring an Array
To declare an array in C#, you need to specify the type of the elements that the array will hold, followed by the name of the array and square brackets that indicate the size of the array. For example:
type[] arrayName = new type[size];
For example, the following code creates an array of integers with 10 elements:
int[] numbers = new int[10];
You can also use the shortcut syntax to create an array and initialize its elements at the same time:
type[] arrayName = new type[] { element1, element2, element3, ... };
For example, the following code creates an array of strings with 3 elements:
string[] names = new string[] { "Alice", "Bob", "Charlie" };
Accessing Array Elements
To access an element of an array, you can use the indexing operator []. The index of the first element is 0, the index of the second element is 1, and so on.
For example, the following code accesses the first element of the names
array:
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
int firstElement = numbers[0]; // firstElement is 1
int lastElement = numbers[4]; // lastElement is 5
Iterating Over an Array
One common way to iterate over an array is to use a for loop. For example:
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
This will print out the elements of the numbers
array one by one.
Modifying Array Elements
To modify an element of an array, you can use the indexing operator to assign a new value to it. For example, the following code changes the second element of the names
array:
names[1] = "Eve";
Multi-Dimensional Arrays
In C#, you can create multi-dimensional arrays by adding additional square brackets to the type. For example, the following code creates a two-dimensional array of integers:
int[,] matrix = new int[3, 3];
To access an element of a multi-dimensional array, you can use multiple indices separated by commas. For example, the following code accesses the element at row 1, column 2 of the matrix
array:
int element = matrix[1, 2];
You can also use loops to iterate through all the elements of a multi-dimensional array. The following code prints all the elements of the matrix
array to the console:
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
I hope this helps! Let me know if you have any questions.