Indexers

  • Indexers enable objects to be indexed in a similar manner to arrays.

  • A get accessor returns a value. A set accessor assigns a value.

  • The this keyword is used to define the indexer.

  • The value keyword is used to define the value being assigned by the set accessor.

  • Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

  • Indexers can be overloaded.

  • Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.

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.

Indexers are used to index instances of a class or struct. The indexed values can then be easily accessed like an array, but without explicitly specifying a type or instance member.

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; }
   }
   // public T this[int i] => arr[i];
}

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

Last updated