Partager via


Indexers (C# Programming Guide) 

Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessors take parameters.

In the following example, a generic class is defined and provided with simple get and set accessor methods as a means for assigning and retrieving values. The class Program creates an instance of this class for storing strings.

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

Indexers Overview

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

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

  • The this keyword is used to define the indexers.

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

  • 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.

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.6.6.3 Indexers

  • 10.2.7.3 Member names reserved for indexers

  • 10.8 Indexers

  • 13.2.4 Interface indexers

See Also

Reference

Properties (C# Programming Guide)

Concepts

C# Programming Guide