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]

A two-dimensional fail-soft array

/*
C#: The Complete Reference
by Herbert Schildt

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

// A two-dimensional fail-soft array.

using System;

class FailSoftArray2D {
int[,] a; // reference to underlying 2D array
int rows, cols; // dimensions
public int Length; // Length is public

public bool errflag; // indicates outcome of last operation

// Construct array given its dimensions.
public FailSoftArray2D(int r, int c) {
rows = r;
cols = c;
a = new int[rows, cols];
Length = rows * cols;
}

// This is the indexer for FailSoftArray2D.
public int this[int index1, int index2] {
// This is the get accessor.
get {
if(ok(index1, index2)) {
errflag = false;
return a[index1, index2];
} else {
errflag = true;
return 0;
}
}

// This is the set accessor.
set {
if(ok(index1, index2)) {
a[index1, index2] = value;
errflag = false;
}
else errflag = true;
}
}

// Return true if indexes are within bounds.
private bool ok(int index1, int index2) {
if(index1 >= 0 & index1 < rows & index2 >= 0 & index2 < cols) return true; return false; } } // Demonstrate a 2D indexer. public class TwoDIndexerDemo { public static void Main() { FailSoftArray2D fs = new FailSoftArray2D(3, 5); int x; // show quiet failures Console.WriteLine("Fail quietly."); for(int i=0; i < 6; i++) fs[i, i] = i*10; for(int i=0; i < 6; i++) { x = fs[i,i]; if(x != -1) Console.Write(x + " "); } Console.WriteLine(); // now, generate failures Console.WriteLine(" Fail with error reports."); for(int i=0; i < 6; i++) { fs[i,i] = i*10; if(fs.errflag) Console.WriteLine("fs[" + i + ", " + i + "] out-of-bounds"); } for(int i=0; i < 6; i++) { x = fs[i,i]; if(!fs.errflag) Console.Write(x + " "); else Console.WriteLine("fs[" + i + ", " + i + "] out-of-bounds"); } } } [/csharp]

Two dimensional indexer

using System;

class MultiplicationTable {
private int[,] MultiplicationArray = new int[10, 10];

public int this[int x, int y] {
get {
return MultiplicationArray[x, y];
}
set {
MultiplicationArray[x, y] = value;
}
}
public MultiplicationTable() {
for (int i = 0; i < 10; i++) { for (int y = 0; y < 10; y++) { MultiplicationArray[i, y] = i * y; } } } } class MultiplicationTableClient { public static void Main(String[] args) { MultiplicationTable MyTable = new MultiplicationTable(); Console.Write("3 x 9 is " + MyTable[3, 9]); } } [/csharp]