User Tools

Site Tools


This is an old revision of the document!

Indexers in C#

Use indexers to access elements in a class (or a struct) that encapsulates a collection. You can define multiple indexers, each with parameters of different types.

Example: Implement an indexer:

class Tagline
    string[] words = "One ring to rule them all".Split();
    // Indexer definition
    public string this [int n]
            if (n < 0 || n > words.length-1)
                throw new IndexOutOfRangeException("Index out of range.");
                return words[n];
            words[n] = value;
// Use the indexer.
Tagline s = new Tagline();
Console.WriteLine(s[3]); // displays the word "rule"

An indexer can take more than one parameter:

public string this [int arg1, string arg2]
    get { ... }
    set { ... }
notes/csharp/indexers.1480388082.txt.gz ยท Last modified: 2016/11/28 by admin