C# Arrays

In C#, an array is a collection of elements of the same type that are stored in contiguous memory locations. Arrays are a useful data structure for holding a group of related values.

Create an Array

To create an array in C#, you can use the new operator followed by the data type and the number of elements in the array:

1// Create an array of integers 2int[] numbers = new int[5];

This creates an integer array with five elements.

You can also initialize an array with values:

1// Create an array of strings and initialize it with values 2string[] names = new string[] { "William", "Jane", "Jack", "Jill" };

This creates a string array with four elements and initializes each element with a string value.

Access the Elements of an Array

You can access the elements of an array by their index. In C#, array indices start at 0, so the first element of an array is at index 0, the second element is at index 1, and so on.

1// Accessing elements of an array 2int[] numbers = new int[] { 1, 2, 3, 4, 5 }; 3Console.WriteLine(numbers[0]); // Output: 1 4Console.WriteLine(numbers[1]); // Output: 2

Change an Array Element

You can change the value of an element in an array by assigning a new value to it:

1// Changing an element in an array 2int[] numbers = new int[] { 1, 2, 3, 4, 5 }; 3numbers[2] = 10; 4Console.WriteLine(numbers[2]); // Output: 10

This code changes the third element in the numbers array from 3 to 10.

Other Ways to Create an Array

In addition to using the new operator to create an array, you can also create an array using the following syntax:

1// Create an array of integers with the following syntax 2int[] numbers = { 1, 2, 3, 4, 5 };

This syntax creates an integer array with five elements and initializes each element with an integer value.

You can also create a multidimensional array by using nested square brackets:

1// Create a two-dimensional array of integers 2int[,] matrix = new int[2, 2] { { 1, 2 }, { 3, 4 } };

This creates a two-dimensional integer array with two rows and two columns.