Implements an indexer and demonstrates that an indexer does not have to operate on an array


   

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

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
// Seedr.cs -- Implements an indexer and demonstrates that an indexer
//             does not have to operate on an array
//
//             Compile this program with the following command line:
//                 C:>csc Seed.cs
//
namespace nsIndexer
{
    using System;
    public class Seedr
    {
        static public void Main ()
        {
            clsIndexed idx = new clsIndexed ();
            Console.WriteLine ("The value is " + idx[900]);
        }
    }
    class clsIndexed
    {
        public int this[int index]
        {
            get
            {
                DateTime now = DateTime.Now;
                Random rand = new Random ((int) now.Millisecond);
                return (rand.Next () % index);
            }
        }
    }
}


           
          


Illustrates the use of an indexer

   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example10_11.cs illustrates the use of an indexer
*/

using System;


// declare the Car class
class Car
{

  // declare two fields
  private string make;
  private string model;

  // define a constructor
  public Car(string make, string model)
  {
    this.make = make;
    this.model = model;
  }

  // define the indexer
  public string this[int index]
  {
    get
    {
      switch (index)
      {
        case 0:
          return make;
        case 1:
          return model;
        default:
          throw new IndexOutOfRangeException();
      }
    }
/*    set
      {
      switch (index)
      {
        case 0:
          this.make = value;
          break;
        case 1:
          this.model = value;
          break;
        default:
          throw new IndexOutOfRangeException();
      }
    }*/
  }

}


public class Example10_11
{

  public static void Main()
  {

    // create a Car object
    Car myCar = new Car("Toyota", "MR2");

    // display myCar[0] and myCar[1]
    Console.WriteLine("myCar[0] = " + myCar[0]);
    Console.WriteLine("myCar[1] = " + myCar[1]);

    // set myCar[0] to "Porsche" and myCar[1] to "Boxster"
    Console.WriteLine("Setting myCar[0] to "Porsche" " +
      "and myCar[1] to "Boxster"");
    myCar[0] = "Porsche";
    myCar[1] = "Boxster";
    // myCar[2] = "Test";  // causes IndeXOutOfRangeException to be thrown

    // display myCar[0] and myCar[1] again
    Console.WriteLine("myCar[0] = " + myCar[0]);
    Console.WriteLine("myCar[1] = " + myCar[1]);

  }

}

           
          


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&#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]);
        }
    }
}

           
          


illustrates the use of an indexer 1


   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example10_11.cs illustrates the use of an indexer
*/

using System;


public class Example10_11a
{

  public static void Main()
  {

    // create a Car object
    Car myCar = new Car("Toyota", "MR2");

    // display myCar[0] and myCar[1]
    Console.WriteLine("myCar[0] = " + myCar[0]);
    Console.WriteLine("myCar[1] = " + myCar[1]);

    // set myCar[0] to "Porsche" and myCar[1] to "Boxster"
    Console.WriteLine("Setting myCar[0] to "Porsche" " +
      "and myCar[1] to "Boxster"");
    myCar[0] = "Porsche";
    myCar[1] = "Boxster";
    // myCar[2] = "Test";  // causes IndeXOutOfRangeException to be thrown

    // display myCar[0] and myCar[1] again
    Console.WriteLine("myCar[0] = " + myCar[0]);
    Console.WriteLine("myCar[1] = " + myCar[1]);

  }

}

// declare the Car class
class Car
{

  // declare two fields
  private string make;
  private string model;

  // define a constructor
  public Car(string make, string model)
  {
    this.make = make;
    this.model = model;
  }

  // define the indexer
  public string this[int index]
  {
    get
    {
      switch (index)
      {
        case 0:
          return make;
        case 1:
          return model;
        default:
          throw new IndexOutOfRangeException();
      }
    }
    set
    {
      switch (index)
      {
        case 0:
          this.make = value;
          break;
        case 1:
          this.model = value;
          break;
        default:
          throw new IndexOutOfRangeException();
      }
    }
  }

}




           
          


Indexer: allow array like index

/*
Learning C#
by Jesse Liberty

Publisher: O'Reilly
ISBN: 0596003765
*/
using System;

namespace Indexers
{
// a simplified ListBox control
public class ListBoxTest
{
private string[] strings;
private int ctr = 0;

// initialize the listbox with strings
public ListBoxTest(params string[] initialStrings)
{
// allocate space for the strings
strings = new String[256];

// copy the strings passed in to the constructor
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}

// add a single string to the end of the listbox
public void Add(string theString)
{
strings[ctr] = theString;
ctr++;
}

// allow array-like access
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
// handle bad index
}
return strings[index];
}
set
{
strings[index] = value;
}
}

// helper method, given a string find
// first matching record that starts with the target
private int findString(string searchString)
{
for (int i = 0;i

Define indexer

/*
Learning C#
by Jesse Liberty

Publisher: O'Reilly
ISBN: 0596003765
*/
using System;

namespace Indexers
{
// a simplified ListBox control
class ListBoxTest
{
private string[] strings;
private int ctr = 0;

// initialize the listbox with strings
public ListBoxTest(params string[] initialStrings)
{
// allocate space for the strings
strings = new String[256];

// copy the strings passed in to the constructor
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}

// add a single string to the end of the listbox
public void Add(string theString)
{
if (ctr >= strings.Length)
{
// handle bad index
}
else
strings[ctr++] = theString;
}

// allow array-like access
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
// handle bad index
}
return strings[index];
}
set
{
// add only through the add method
if (index >= ctr )
{
// handle error
}
else
strings[index] = value;
}
}

// publish how many strings you hold
public int GetNumEntries()
{
return ctr;
}

}

public class TesterListBoxTest
{
[STAThread]
static void Main()
{
// create a new listbox and initialize
ListBoxTest lbt =
new ListBoxTest(“Hello”, “World”);

Console.WriteLine(“After creation…”);
for (int i = 0;i

Create a specifiable range array class

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

/* Create a specifiable range array class.
The RangeArray class allows indexing
to begin at some value other than zero.
When you create a RangeArray, you specify
the beginning and ending index. Negative
indexes are also allowed. For example,
you can create arrays that index from -5 to 5,
1 to 10, or 50 to 56.
*/

using System;

class RangeArray {
// private data
int[] a; // reference to underlying array
int lowerBound; // lowest index
int upperBound; // greatest index

// data for properties
int len; // underlying var for Length property
bool errflag; // underlying var for outcome

// Construct array given its size.
public RangeArray(int low, int high) {
high++;
if(high <= low) { Console.WriteLine("Invalid Indices"); high = 1; // create a minimal array for safety low = 0; } a = new int[high - low]; len = high - low; lowerBound = low; upperBound = --high; } // Read-only Length property. public int Length { get { return len; } } // Read-only Error property. public bool Error { get { return errflag; } } // This is the indexer for RangeArray. public int this[int index] { // This is the get accessor. get { if(ok(index)) { errflag = false; return a[index - lowerBound]; } else { errflag = true; return 0; } } // This is the set accessor set { if(ok(index)) { a[index - lowerBound] = value; errflag = false; } else errflag = true; } } // Return true if index is within bounds. private bool ok(int index) { if(index >= lowerBound & index <= upperBound) return true; return false; } } // Demonstrate the index-range array. public class RangeArrayDemo { public static void Main() { RangeArray ra = new RangeArray(-5, 5); RangeArray ra2 = new RangeArray(1, 10); RangeArray ra3 = new RangeArray(-20, -12); // Demonstrate ra Console.WriteLine("Length of ra: " + ra.Length); for(int i = -5; i <= 5; i++) ra[i] = i; Console.Write("Contents of ra: "); for(int i = -5; i <= 5; i++) Console.Write(ra[i] + " "); Console.WriteLine(" "); // Demonstrate ra2 Console.WriteLine("Length of ra2: " + ra2.Length); for(int i = 1; i <= 10; i++) ra2[i] = i; Console.Write("Contents of ra2: "); for(int i = 1; i <= 10; i++) Console.Write(ra2[i] + " "); Console.WriteLine(" "); // Demonstrate ra3 Console.WriteLine("Length of ra3: " + ra3.Length); for(int i = -20; i <= -12; i++) ra3[i] = i; Console.Write("Contents of ra3: "); for(int i = -20; i <= -12; i++) Console.Write(ra3[i] + " "); Console.WriteLine(" "); } } [/csharp]