Search⌘ K
AI Features

Indexers

Explore how to implement and use indexers in C# to access and manipulate object data using array-style syntax. Understand defining indexers with get and set accessors, overloading them for different parameter types, and applying these concepts to custom classes like Garage and Car.

We'll cover the following...

Indexers are special constructs that allow us to access an object’s content through an index. They add an array-like behavior to custom types.

For example, to access the second item of an array, we use an index, 1:

C# 14.0
int[] integerArray = { 2, 6, 8, 1 };
Console.WriteLine(integerArray[1]);
  • Line 1: We initialize an integer array with four values.

  • Line 2: We access and print the element at index 1 (the second element, 6).

We can use indexers to interact with custom types using the same [] syntax used for arrays.

Syntax

Indexers use syntax similar to properties, including get and set blocks. However, indexers do not have names; we define them using the this keyword followed by [].

// Multiple parameters can be supplied
return_type this[parameter_type]
{
get { }
set { }
}
General syntax for defining an indexer
  • ...