Wednesday, January 16, 2013

Indexers

Indexers allow your class to be used just like an array. On the inside of a class, you manage a collection of values any way you want.

using System;

///
///
     A simple indexer example.
///

class IntIndexer
{
    private string[] myData;

    public IntIndexer(int size)
    {
        myData =
new string[size];

        for (int i=0; i < size; i++)
        {
            myData[i] = "empty";
        }
    }

    public
string this[int pos]
    {
        get
       {
            return myData[pos];
        }
        set
       {
            myData[pos] =
value;
        }
    }

    static
void Main(string[] args)
    {
        int size = 10;

        IntIndexer myInd =
new IntIndexer(size);

        myInd[9] = "Some Value";
        myInd[3] = "Another Value";
        myInd[5] = "Any Value";

        Console.WriteLine("\nIndexer Output\n");

        for
(int i=0; i < size; i++)
        {
            Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
        }
    }
}

No comments:

Post a Comment