Indexers

Learn to work with classes as if they were arrays.

Introduction

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

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

int[] integerArray = new int[] { 2, 6, 8, 1 };
Console.WriteLine(integerArray[1]);

We can work with custom types in a similar fashion with indexers as we do with [] to access an array’s contents.

Syntax

In terms of syntax, indexers are like properties because they have get and set blocks. Unlike properties, they don’t have names, but are defined by a this keyword followed by []:

// Multiple parameters can be supplied
return_type this[parameter_type]
{
	get { }
	set { }
}

Usage

Let’s look at the following example for better understanding:

Get hands-on with 1200+ tech skills courses.