| title | Indexers (C# Programming Guide) | ||
|---|---|---|---|
| ms.date | 03/10/2017 | ||
| ms.prod | .net | ||
| ms.technology |
|
||
| ms.topic | article | ||
| f1_keywords |
|
||
| helpviewer_keywords |
|
||
| ms.assetid | 022cd27d-d5e0-4cfe-8b97-dc018cc3355d | ||
| caps.latest.revision | 29 | ||
| author | BillWagner | ||
| ms.author | wiwagn |
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.
[!code-csharpindexers#1]
Note
For more examples, see Related Sections.
It is common for an indexer's get or set accessor to consist of a single statement that either returns or sets a value. Expression-bodied members provide a simplified syntax to support this scenario. Starting with C# 6, a read-only indexer can be implemented as an expression-bodied member, as the following example shows.
[!code-csharpindexers#2]
Note that => introduces the expression body, and that the get keyword is not used.
Starting with C# 7, both the get and set accessor can be an implemented as expression-bodied members. In this case, both get and set keywords must be used. For example:
[!code-csharpindexers#3]
-
Indexers enable objects to be indexed in a similar manner to arrays.
-
A
getaccessor returns a value. Asetaccessor 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
setindexer. -
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.
[!INCLUDECSharplangspec]