CHAPTER 16

image

Indexers

Indexers allow an object to be treated as an array. They are declared in the same way as properties, except that the this keyword is used instead of a name and their accessors take parameters. In the example below, the indexer corresponds to an object array called data, so the type of the indexer is set to object.

class MyArray{   object[] data = new object[10];    public object this[int i]  {     get    {       return data[i];    }     set    {       data[i] = value;    }   } } 

The get accessor returns the specified element from the object array, and the set accessor inserts the value into the specified element. With the ...

Get C# Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.