0
0
C Sharp (C#)programming~5 mins

Array indexing and access in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Arrays store many items in order. Indexing helps you find and use each item quickly.

You want to get a specific item from a list of things, like the first or last name in a list.
You need to change one item in a group, like updating a score in a game.
You want to check or use all items one by one, like printing all colors in a palette.
Syntax
C Sharp (C#)
class Program
{
    static void Main()
    {
        int[] numbers = {10, 20, 30, 40};
        int firstNumber = numbers[0]; // Access first item
        numbers[2] = 35; // Change third item
    }
}

Array indexes start at 0, so the first item is at index 0.

Accessing an index outside the array size causes an error.

Examples
Example of an empty array. No items to access.
C Sharp (C#)
int[] emptyArray = new int[0];
// emptyArray has no items
// Accessing any index will cause an error
Array with one item. Only index 0 is valid.
C Sharp (C#)
int[] singleItemArray = { 100 };
int onlyItem = singleItemArray[0]; // 100
// singleItemArray[1] would cause an error
Accessing first and last items in a small array.
C Sharp (C#)
string[] fruits = { "apple", "banana", "cherry" };
string firstFruit = fruits[0]; // "apple"
string lastFruit = fruits[2]; // "cherry"
Sample Program

This program shows how to access and change items in an array by their index. It prints the colors before and after changing one.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        string[] colors = { "red", "green", "blue" };

        Console.WriteLine("Colors before change:");
        foreach (string color in colors)
        {
            Console.WriteLine(color);
        }

        // Access and print the first color
        Console.WriteLine($"First color: {colors[0]}");

        // Change the second color
        colors[1] = "yellow";

        Console.WriteLine("Colors after change:");
        foreach (string color in colors)
        {
            Console.WriteLine(color);
        }
    }
}
OutputSuccess
Important Notes

Accessing an array element by index is very fast, O(1) time complexity.

Arrays use a fixed amount of memory based on their size (space complexity O(n)).

Common mistake: Trying to access an index outside the array size causes a runtime error (IndexOutOfRangeException).

Use array indexing when you know the position of the item you want. Use loops to access all items.

Summary

Arrays store items in order and use zero-based indexes to find them.

You can read or change an item by using its index inside square brackets.

Always make sure the index is inside the array size to avoid errors.