Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Element access: array[index]

The expression array[index] reads or changes an array element. Square brackets [] also provide indexer access; the meaning of their arguments then depends on the particular type.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

array[index]
array[index] = value;
matrix[row, column]
objectWithIndexer[key]

array[index] identifies an array element: array is an expression that returns an array, and index specifies the position. In an ordinary one-dimensional C# array, indices start at 0 and end at array.Length - 1. Reading retrieves the element's value, while array[index] = value stores a new value without changing the array's length.

An index outside the array bounds causes IndexOutOfRangeException; access through a reference equal to null causes NullReferenceException. An empty array has no valid element index. array?[index] skips access when the array is null, but does not protect against an invalid index for an existing array.

A rectangular array uses one index per dimension, such as matrix[row, column]. A jagged array uses successive access operations, such as rows[row][column]. The same [] notation supports object indexers, whose argument can be a string key, for example. Their reading, writing, and exception rules depend on the type; do not assume array behavior. You cannot overload [] directly — custom types provide indexers instead.

The brackets in int[] declare an array type; they do not read an element. The example demonstrates basic element reading and writing, without features requiring a preview language version.

Examples

using System;

class Program
{
    static void Main()
    {
        int[] array = { 10, 20, 30 };
        int index = 1;
        Console.WriteLine(array[index]);
        array[index] = 25;
        Console.WriteLine(array[index]);
        Console.WriteLine(array[0]);
    }
}

Result

20
25
10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources