Indexers are known as smart arrays in C#.

It allows the instances of a class to be indexed in the same way as an array.


public int this[int index]    // Indexer declaration

Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.

The following example defines a generic class with simple get and set accessor methods to assign and retrieve values. The Program class creates an instance of this class for storing strings.


using System;

class SampleCollection<T>
   // Declare an array to store the data elements.
   private T[] arr = new T[100];

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
      get { return arr[i]; }
      set { arr[i] = value; }

class Program
   static void Main()
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World";
// The example displays the following output:
//       Hello, World.