Here is a code sample that demonstrates the usage of an indexer on a class. In the example below, with no error checking mind you, we can add data from an add method or index into it. Call the Usage static method to demonstrate its usage:

public class ShowConcepts
{
    // This static method is only here for example usage
    public static void Usage()
    {
        ShowConcepts sc = new ShowConcepts();

        sc.Add(8675309, "Jenny");
        sc[90125] = "Yes";
        Console.WriteLine(sc[8675309]); // Prints Jenny
    }

    Dictionary<int, string> _myData = new Dictionary<int,string>();

    // The ability to add a value via an add method.
    public void Add(int key, string value)
    {
        _myData.Add(key, value);
    }

    // Index the data here
    public string this[int key]
    {
        get
        {
            return _myData[key];
        }
        set
        {
            _myData[key] = value;
        }
    }
}
Share