Indexers (C# Programming Guide)
Indexers (C# Programming Guide)
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble 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 of assigning and retrieving values. The
Program class creates an instance of this class for storing strings.
C#
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
https://msdn.microsoft.com/enus/library/6x16t2tx.aspx 1/3
7/19/2015 Indexers (C# Programming Guide)
{
static void Main(string[] args)
{
// Declare an instance of the SampleCollection type.
SampleCollection<string> stringCollection = new SampleCollection<string>();
Note
Indexers Overview
Indexers enable objects to be indexed in a similar manner to arrays.
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 have more than one formal parameter, for example, when accessing a two‐dimensional array.
https://msdn.microsoft.com/enus/library/6x16t2tx.aspx 2/3
7/19/2015 Indexers (C# Programming Guide)
Related Sections
Using Indexers ﴾C# Programming Guide﴿
C# Language Specification
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
See Also
Reference
Properties ﴾C# Programming Guide﴿
Concepts
C# Programming Guide
© 2015 Microsoft
https://msdn.microsoft.com/enus/library/6x16t2tx.aspx 3/3