Arrays store many items in order. Indexing helps you find and use each item quickly.
Array indexing and access in 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.
int[] emptyArray = new int[0]; // emptyArray has no items // Accessing any index will cause an error
int[] singleItemArray = { 100 }; int onlyItem = singleItemArray[0]; // 100 // singleItemArray[1] would cause an error
string[] fruits = { "apple", "banana", "cherry" };
string firstFruit = fruits[0]; // "apple"
string lastFruit = fruits[2]; // "cherry"This program shows how to access and change items in an array by their index. It prints the colors before and after changing one.
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); } } }
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.
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.