Implements an indexer in a class : Indexer « Class Interface « C# / C Sharp






Implements an indexer in a class

Implements an indexer in a class
/*
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[x] = rand.Next() % 501;
        }
        int [] Arr;
        public int this[int index]
        {
            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]);
        }
    }
}

           
       








Related examples in the same category

1.indexed properties
2.Indexer with complex logic
3.Use an indexer to create a fail-soft arrayUse an indexer to create a fail-soft array
4.Overload the FailSoftArray indexerOverload the FailSoftArray indexer
5.Indexers don't have to operate on actual arraysIndexers don't have to operate on actual arrays
6.Two dimensional indexer
7.A two-dimensional fail-soft arrayA two-dimensional fail-soft array
8.Create a specifiable range array classCreate a specifiable range array class
9.Define indexerDefine indexer
10.Indexer: allow array like indexIndexer: allow array like index
11.illustrates the use of an indexer 1illustrates the use of an indexer 1
12.Illustrates the use of an indexer
13.Implements an indexer and demonstrates that an indexer does not have to operate on an arrayImplements an indexer and demonstrates that an indexer does not have to operate on an array
14.C# Properties and Indexers
15.Indexing with an Integer IndexIndexing with an Integer Index
16.Indexing with an String Index
17.Indexing with Multiple ParametersIndexing with Multiple Parameters
18.Return class object from indexer