Interfaces - Properties


In an interface, properties may be specified without a body. Following is the syntax for specifying properties in interfaces.

interface interface-name
{
 ...
 property-type property-name {get; set; }
 ...
}

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

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

// Interface4 - Interface Properties

using System;

public interface ISequence
{
    uint Next { get; set;}  // Interface Property
    void Reset();
}

class Primes : ISequence
{
    uint start;
    uint current;

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

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

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

    public void Reset()
    {
        current = start;
    }

    bool IsPrime()
    {
        if (current < 2) return false;

        bool is_prime = true;

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

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

        return is_prime;
    }
}

class Program
{
    static void Main()
    {
        ISequence s = new Primes();

        for (uint i = 0; i < 3; i++)
            Console.WriteLine("Next Prime: {0}", s.Next);

        Console.WriteLine("Resetting");
        s.Reset();

        for (uint i = 0; i < 3; i++)
            Console.WriteLine("Next Prime: {0}", s.Next);

        Console.WriteLine("Starting at 100");
        s.Next = 100;

        for (uint i = 0; i < 3; i++)
            Console.WriteLine("Next Prime: {0}", s.Next);
    }
}