C# Access Array Elements Example

In this source code example, we will demonstrate how to access elements from an Array in C# with an example.

After an array is created, its elements can be accessed by their index. An index is a number placed inside square brackets which follow the array name.

C# Access Array Elements Example

In the below C# program, we create an array of string names. We access each of the elements by its index and print them to the terminal.

using System;

public class ArrayDemo
{
    public static void Main(string[] args)
    {
        string[] fruits = { "Banana", "Mango", "Apple", "Watermelon" };

        Console.WriteLine(fruits[0]);
        Console.WriteLine(fruits[1]);
        Console.WriteLine(fruits[2]);
        Console.WriteLine(fruits[3]);
        
        Console.WriteLine("************ Access elements in noramal for loop *************");
        
        for (int i = 0; i < fruits.Length; i++)
        {
            Console.WriteLine(fruits[i]);
        }
        
        Console.WriteLine("************ Access elements in foreach loop *************");
        
        foreach (string i in fruits)
        {
            Console.WriteLine(i);
        }
    }
}

Output:

Banana
Mango
Apple
Watermelon
************ Access elements in noramal for loop *************
Banana
Mango
Apple
Watermelon
************ Access elements in foreach loop *************
Banana
Mango
Apple
Watermelon




Comments