Light Mode Image

C# Array

An array is a collection of elements of the same type that are stored in contiguous memory locations. Arrays provide a way to store and access multiple values using a single variable name.

 

Example of an array in C#.

using System;

class Program
{
    static void Main()
    {
        // Declare and initialize an array of integers
        int[] numbers = { 1, 2, 3, 4, 5 };

        // Accessing elements of the array
        Console.WriteLine("First element: " + numbers[0]);
        Console.WriteLine("Second element: " + numbers[1]);

        // Modifying an element of the array
        numbers[2] = 10;
        Console.WriteLine("Modified third element: " + numbers[2]);

        // Iterating through the array using a loop
        Console.WriteLine("All elements:");
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine(numbers[i]);
        }
    }
}

 

In this example:

1. int[] numbers declares an array of integers.

2.{ 1, 2, 3, 4, 5 } initializes the array with five elements.

3. Array indices start at 0, so numbers[0] is the first element, numbers[1] is the second, and so on.

4. The length of the array is obtained using numbers.Length.

5. The array elements can be accessed and modified using square brackets ([]).

 

You can create arrays of other data types in a similar manner, such as string[] for an array of strings or double[] for an array of double-precision floating-point numbers.

 

Additionally, C# provides various methods and properties for working with arrays, such as Array.Sort() for sorting elements and Array.IndexOf() for finding the index of a specific element.