Indexers

Indexers enable indexing of classes and structs exactly like arrays.

Indexers function like properties, using the get and set accessors, except the accessors have parameters. The this keyword is employed in defining indexers. The value keyword defines the value assigned by the set indexer. Indexers do not require an integer value for the index. The developer defines the look-up tool.

Review general indexer syntax below:

class TheCollection
{
	private dataType[] arrayName = new dataType[4]{1, 2, 3, 4};

	public datatype this[int index]
	{
		get
		{
			return arrayName[index];
		}
		set
		{
			arrayName[index] = value;
		}
	}
}

Indexers can be overloaded, and have multiple formal parameters. They are also not limited to the integer data type, whether using a single or multiple parameters.

Some indexers only retrieve an immediate expression result. C# provides a shortcut for these indexers through employing the “=>” character:

public Product this[long idnum] => stock.LookupProduct(idnum);

Indexers make applications vulnerable. Secure the application through error-handling strategies for invalid indexes, and through restricting access to get and set accessors.