Zurück

C# Indexer

Accessing Class Data like Array Elements


Indexer

C# introduces a special kind of class method called an indexer. This allows you to access elements of data inside a class using a method that makes the data look like array elements.

An indexer is a smart array in exactly the same way that a property is a smart field. In other words, the syntax that you use for an indexer is exactly the same as the syntax you use for an array.

You declare an indexer property within a class using the following syntax:

type this [type argument]{get; set;}

The return type determines the type of object that will be returned by the indexer, while the type argument specifies what kind of argument will be used to index into the collection that contains the target objects. Although it is common to use integers as index values, you can index a collection on other types as well, including strings. You can even provide an indexer with multiple parameters to create a multidimensional array!

The this keyword is a reference to the object in which the indexer appears. As with a normal property, you also must define get and set accessors, which determine how the requested object is retrieved from or assigned to its collection.

Example

The following example declares a listbox control (SimpleListBox) that contains a simple array (myStrings) and a simple indexer for accessing its contents.

using System;
using System.Text;

namespace SimpleIndexer
{
     // Simplified ListBox control
    public class SimpleListBox
    {
        // The ListBox contain an Arry of Strings which are
        // accessed by the Indexer

        private string[] strArr;
        private int count = 0;

        // Constructor: Initialize the ListBox with strings
        public SimpleListBox(params string[] pStrings)
        {
            // Allocate space for the strings
            strArr = new String[256];

            // Copy the strings passed in to the constructor
            foreach (string s in pStrings)
            {
                strArr[count++] = s;
            }
        }

        // Add a single string to the end of the ListBox
        public void Add(string pString)
        {
            if (count <= strArr.Length)
            {
                strArr[count++] = pString;
            }
        }

        // Indexer: Allow array-like access
        public string this[int index]
        {
            get
            {
                if (index >= 0 && index <= strArr.Length)
                {
                    return strArr[index];
                }
                else
                {
                    return null;
                }
            }
            set
            {
                if (index <= count)
                {
                    strArr[index] = value;
                }
            }
        }


        // Publish how many strings you hold
        public int GetNumEntries()
        {
            return count;
        }
    }

    // Test Class
    public class Tester
    {
        static void Main()
        {
            // Create a new ListBox and initialize
            SimpleListBox lbt = new SimpleListBox("Hello", "World");

            // Add a few strings
            lbt.Add("Who");
            lbt.Add("Is");
            lbt.Add("John");
            lbt.Add("Galt");

            // Test the Indexer access (Write), so you
            // don't need the Add Method anymore.

            string subst = "Universe";
            lbt[1] = subst;

            // Access all the strings by the Indexer (Read)
            for (int i = 0; i < lbt.GetNumEntries(); i++)
            {
                Console.WriteLine("lbt[{0}]: {1}", i, lbt[i]);
            }
        }
    }
}

The key method of SimpleListBox, however, is the indexer. An indexer is unnamed, so use the this keyword:

public string this[int index]

The syntax of the indexer is very similar to that for properties. There is either a get() method, a set() method, or both.