Implements an indexer in a class

image_pdfimage_print

   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

//
// Indexer.cs -- Implements an indexer in a class
//
//               Compile this program with the following command line:
//                   C:>csc Indexer.cs
//
namespace nsIndexer
{
    using System;
    
    public class Indexer
    {
        static public void Main ()
        {
            clsIndexed idx = new clsIndexed (10);
            Console.WriteLine ("The value is " + idx[3]);
            idx.Show (3);
        }
    }
    class clsIndexed
    {
        public clsIndexed (int elements)
        {
             DateTime now = DateTime.Now;
             Random rand = new Random ((int) now.Millisecond);
             Arr = new int [elements];
             for (int x = 0; x < Arr.Length; ++x)
                 Arr&#91;x&#93; = rand.Next() % 501;
        }
        int &#91;&#93; Arr;
        public int this&#91;int index&#93;
        {
            get
            {
                if ((index < 0) || (index > Arr.Length))
                    throw (new ArgumentOutOfRangeException());
                return (Arr[index]);
            }
        }
        public void Show (int index)
        {
            Console.WriteLine ("The value is " + Arr[index]);
        }
    }
}