Interfaces - Indexers


Following is the syntax for specifying a 1 dimensional indexer in an interface.

interface interface-name
{
 ...
 element-type this[index-type index] {get; set; }
 ...
}

For a read-only indexer, only the get accessor will be present. For a write-only indexer, only the set accessor will be present.

Below is a rewrite of the ISequence interface that uses indexers.

// Interface5 - Interface Indexers

using System;

public interface ISequence
{
    uint Next { get; set;}
    void Reset();
    uint this[uint index] { get; }  // Interface Indexer
}

class Primes : ISequence
{
    uint start;
    uint current;

    public Primes()
    {
        start = current = 1;
    }

    public uint Next
    {
        get
        {
            do
            {
                current++;
            } while (!IsPrime(current));

            return current;
        }
        set
        {
            current = start = value;
        }
    }

    public void Reset()
    {
        current = start;
    }

    public uint this[uint index] // Indexer Implementation
    {
        get
        {
            uint j = 2;
            for (uint i = 0; i < index; i++)
            {
                do
                {
                    j++;
                } while (!IsPrime(j));

            }
            return j;
        }
    }

    static bool IsPrime(uint i)
    {
        if (i < 2) return false;

        bool is_prime = true;

        uint j = 2;
        uint limit = (uint)Math.Sqrt(i);

        while (j <= limit)
        {
            if (i % j == 0) { is_prime = false; break; }
            j++;
        }

        return is_prime;
    }
}

class Program
{
    static void Main()
    {
        ISequence s = new Primes();
                
        for (uint i = 0; i < 10; i++)
            Console.WriteLine("Prime[{0}] = {1}", i, s[i]);

    }
}

The output of the program is shown below.

Prime[0] = 2
Prime[1] = 3
Prime[2] = 5
Prime[3] = 7
Prime[4] = 11
Prime[5] = 13
Prime[6] = 17
Prime[7] = 19
Prime[8] = 23
Prime[9] = 29

It is apparent that using computation, an indexer for prime numbers can be programmed. No formula for primes has been found by mathematicians in thousands of years of searching for one. The larger the index value the more intensive the computation of the value becomes - so the algorithm is not particularly efficient for large indexes.