Csharp/C Sharp/Class Interface/Indexer

Материал из .Net Framework эксперт
Версия от 11:39, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

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("\nFail 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"); 
    } 
  } 
}


C# Properties and Indexers

using System;
public PropertiesIndexers
{
    public static void Main()
    {
        Circle c = new Circle();
        c.Radius = 35;
    }
}
class Circle
{
    public int Radius
    {
        get
        {
            return(radius);
        }
        set
        {
            radius = value;
            Draw();
        }
    }
    public void Draw()
    {
    }
    int radius;
}


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("\n"); 
 
    // 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("\n"); 
 
    // 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("\n"); 
 
  }  
}


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<lbt.GetNumEntries();i++)
           {
               Console.WriteLine("lbt[{0}]: {1}",i,lbt[i]);
           }
           // add a few strings
           lbt.Add("Who");
           lbt.Add("Is");
           lbt.Add("John");
           lbt.Add("Galt");
           Console.WriteLine("\nAfter adding strings...");
           for (int i = 0;i<lbt.GetNumEntries();i++)
           {
               Console.WriteLine("lbt[{0}]: {1}",i,lbt[i]);
           }

           // test the access
           string subst = "Universe";
           lbt[1] = subst;
           // access all the strings
           Console.WriteLine("\nAfter editing strings...");
           for (int i = 0;i<lbt.GetNumEntries();i++)
           {
               Console.WriteLine("lbt[{0}]: {1}",i,lbt[i]);
           }
       }
    }
 }


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


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();
      }
    }
  }
}


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);
            }
        }
    }
}


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


indexed properties

 
using System;
public class Starter {
    public static void Main() {
        Names obj = new Names();
        Console.WriteLine(obj[1]);
    }
}
public class Names {
    object[,] _names ={{"V", 27},{"B", 35},{"D", 29}};
    public object this[int index] {
        get {
            return _names[index, 0] + " " + _names[index, 1];
        }
    }
}


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<strings.Length;i++)
             {
                 if (strings[i].StartsWith(searchString))
                 {
                     return i;
                 }
             }
             return -1;
         }
         // index on string
         public string this[string index]
         {
             get
             {
                 if (index.Length == 0)
                 {
                     // handle bad index
                 }
                 return this[findString(index)];
             }
             set
             {
                 strings[findString(index)] = value;
             }
         }
         // publish how many strings you hold
         public int GetNumEntries()
         {
             return ctr;
         }
     }

    public class TesterIndexersList
    {
       public void Run()
       {
           // create a new listbox and initialize
           ListBoxTest lbt =
               new ListBoxTest("Hello", "World");
           // add a few strings
           lbt.Add("Who");
           lbt.Add("Is");
           lbt.Add("John");
           lbt.Add("Galt");
           // test the access
           string subst = "Universe";
           lbt[1] = subst;
           lbt["Hel"] = "GoodBye";
           // lbt["xyz"] = "oops";

           // access all the strings
           for (int i = 0; i<lbt.GetNumEntries(); i++)
           {
               Console.WriteLine("lbt[{0}]: {1}",i,lbt[i]);
           }

       }
       [STAThread]
       static void Main()
       {
          TesterIndexersList t = new TesterIndexersList();
          t.Run();
       }
    }
 }


Indexers don"t have to operate on actual arrays

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Indexers don"t have to operate on actual arrays. 
 
using System; 
 
class PwrOfTwo {  
 
  /* Access a logical array that contains 
     the powers of 2 from 0 to 15. */ 
  public int this[int index] { 
    // Compute and return power of 2. 
    get { 
      if((index >= 0) && (index < 16)) return pwr(index); 
      else return -1; 
    } 
 
    // there is no set accessor 
  } 
 
  int pwr(int p) { 
    int result = 1; 
 
    for(int i=0; i<p; i++) 
      result *= 2; 
     
    return result; 
  } 
}  
  
public class UsePwrOfTwo {  
  public static void Main() {  
    PwrOfTwo pwr = new PwrOfTwo(); 
 
    Console.Write("First 8 powers of 2: "); 
    for(int i=0; i < 8; i++) 
      Console.Write(pwr[i] + " "); 
    Console.WriteLine(); 
 
    Console.Write("Here are some errors: "); 
    Console.Write(pwr[-1] + " " + pwr[17]); 
 
    Console.WriteLine(); 
  } 
}


Indexer with complex logic

 
using System;
class MyValue {
    private String[] Cards = new String[52];
    public String this[int index] {
        get {
            return Cards[index];
        }
        set {
            Cards[index] = value;
        }
    }
    public String this[String CardName] {
        get {
            for (int i = 0; i < 52; i++) {
                if (Cards[i] == CardName)
                    return Cards[i];
            }
            return Cards[0];
        }
        set {
            for (int i = 0; i < 52; i++) {
                if (Cards[i] == CardName)
                    Cards[i] = value;
            }
        }
    }
    public MyValue() {
        int y = 0;
        int i = 0;
        while (i < 52) {
            for (int x = 0; x < 13; x++) {
                switch (y) {
                    case 0:
                        Cards[i] = (x + 1) + " A";
                        break;
                    case 1:
                        Cards[i] = (x + 1) + " B";
                        break;
                    case 2:
                        Cards[i] = (x + 1) + " C";
                        break;
                    case 3:
                        Cards[i] = (x + 1) + " D";
                        break;
                }
                if (y == 3)
                    y = 0;
                else
                    y++;
                i++;
            }
        }
    }
}
class MyValueClient {
    public static void Main() {
        MyValue PokerDeck = new MyValue();
        String FourOfHearts = PokerDeck["4 of Hearts"];
        Console.WriteLine(FourOfHearts);
    }
}


Indexing with an Integer Index

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 19 - Indexers and Enumerators\Indexing with an Integer Index
// copyright 2000 Eric Gunnerson
using System;
using System.Collections;
class DataValue
{
    public DataValue(string name, object data)
    {
        this.name = name;
        this.data = data;
    }
    public string Name
    {
        get
        {
            return(name);
        }
        set
        {
            name = value;
        }
    }
    public object Data
    {
        get
        {
            return(data);
        }
        set
        {
            data = value;
        }
    }
    string    name;
    object data;
}
class DataRow
{
    public DataRow()
    {
        row = new ArrayList();
    }
    
    public void Load() 
    {
        /* load code here */ 
        row.Add(new DataValue("Id", 5551212));
        row.Add(new DataValue("Name", "Fred"));
        row.Add(new DataValue("Salary", 2355.23m));
    }
    
    // the indexer
    public DataValue this[int column]
    {
        get
        {
            return((DataValue) row[column - 1]);
        }
        set
        {
            row[column - 1] = value;
        }
    }
    ArrayList    row;    
}
public class IndexingwithanIntegerIndex
{
    public static void Main()
    {
        DataRow row = new DataRow();
        row.Load();
        Console.WriteLine("Column 0: {0}", row[1].Data);
        row[1].Data = 12;    // set the ID
    }
}


Indexing with an String Index

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 19 - Indexers and Enumerators\Indexing with an String Index
// copyright 2000 Eric Gunnerson
using System;
using System.Collections;
class DataValue
{
    public DataValue(string name, object data)
    {
        this.name = name;
        this.data = data;
    }
    public string Name
    {
        get
        {
            return(name);
        }
        set
        {
            name = value;
        }
    }
    public object Data
    {
        get
        {
            return(data);
        }
        set
        {
            data = value;
        }
    }
    string    name;
    object data;
}
class DataRow
{
    public DataRow()
    {
        row = new ArrayList();
    }
    
    public void Load() 
    {
        /* load code here */ 
        row.Add(new DataValue("Id", 5551212));
        row.Add(new DataValue("Name", "Fred"));
        row.Add(new DataValue("Salary", 2355.23m));
    }
    
    public DataValue this[int column]
    {
        get
        {
            return( (DataValue) row[column - 1]);
        }
        set
        {
            row[column - 1] = value;
        }
    }
    int FindColumn(string name)
    {
        for (int index = 0; index < row.Count; index++)
        {
            DataValue dataValue = (DataValue) row[index];
            if (dataValue.Name == name)
            return(index);
        }
        return(-1);
    }
    public DataValue this[string name]
    {
        get
        {
            return( (DataValue) this[FindColumn(name)]);
        }
        set
        {
            this[FindColumn(name)] = value;
        }
    }
    ArrayList    row;    
}
public class IndexingwithanStringIndex
{
    public static void Main()
    {
        DataRow row = new DataRow();
        row.Load();
        DataValue val = row["Id"];
        Console.WriteLine("Id: {0}", val.Data);
        Console.WriteLine("Salary: {0}", row["Salary"].Data);
        row["Name"].Data = "Barney";    // set the name
        Console.WriteLine("Name: {0}", row["Name"].Data);
    }
}


Indexing with Multiple Parameters

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 19 - Indexers and Enumerators\Indexing with Multiple Parameters
// copyright 2000 Eric Gunnerson
using System;
class Player
{
    string name;
    
    public Player(string name)
    {
        this.name = name;
    }
    
    public override string ToString()
    {
        return(name);
    }
}
class Board
{
    Player[,] board = new Player[8, 8];
    
    int RowToIndex(string row)
    {
        string temp = row.ToUpper();
        return((int) temp[0] - (int) "A");
    }
    
    int PositionToColumn(string pos)
    {
        return(pos[1] - "0" - 1);
    }
    
    public Player this[string row, int column]
    {
        get
        {
            return(board[RowToIndex(row), column - 1]);
        }
        set
        {
            board[RowToIndex(row), column - 1] = value;
        }
    }    
    
    public Player this[string position]
    {
        get
        {
            return(board[RowToIndex(position),
            PositionToColumn(position)]);
        }
        set
        {
            board[RowToIndex(position),
            PositionToColumn(position)] = value;
        }
    }    
}
public class IndexingwithMultipleParameters
{
    public static void Main()
    {
        Board board = new Board();
        
        board["A", 4] = new Player("White King");
        board["H", 4] = new Player("Black King");
        
        Console.WriteLine("A4 = {0}", board["A", 4]);
        Console.WriteLine("H4 = {0}", board["H4"]);
    }
}


Overload the FailSoftArray indexer

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Overload the FailSoftArray indexer. 
  
using System;  
  
class FailSoftArray {   
  int[] a;    // reference to underlying array   
  
  public int Length; // Length is public  
  
  public bool errflag; // indicates outcome of last operation  
    
  // Construct array given its size.  
  public FailSoftArray(int size) {  
    a = new int[size];  
    Length = size;   
  }  
  
  // This is the int indexer for FailSoftArray.  
  public int this[int index] {  
    // This is the get accessor.  
    get {  
      if(ok(index)) {  
        errflag = false;  
        return a[index];  
      } else {  
        errflag = true;  
        return 0;  
      }  
    }  
  
    // This is the set accessor  
    set {  
      if(ok(index)) {  
        a[index] = value;  
        errflag = false;  
      }  
      else errflag = true;  
    }  
  }  
  
  /* This is another indexer for FailSoftArray. 
     This index takes a double argument.  It then 
     rounds that argument to the nearest integer 
     index. */  
  public int this[double idx] {  
    // This is the get accessor.  
    get {  
      int index; 
 
      // round to nearest int 
      if( (idx - (int) idx) < 0.5) index = (int) idx; 
      else index = (int) idx + 1; 
 
      if(ok(index)) {  
        errflag = false;  
        return a[index];  
      } else {  
        errflag = true;  
        return 0;  
      }  
    }  
  
    // This is the set accessor  
    set {  
      int index; 
 
      // round to nearest int 
      if( (idx - (int) idx) < 0.5) index = (int) idx; 
      else index = (int) idx + 1; 
 
      if(ok(index)) {  
        a[index] = value;  
        errflag = false;  
      }  
      else errflag = true;  
    }  
  }  
  
  // Return true if index is within bounds.  
  private bool ok(int index) {  
   if(index >= 0 & index < Length) return true;  
   return false;  
  }  
}   
   
// Demonstrate the fail-soft array.  
public class FSDemo1 {   
  public static void Main() {   
    FailSoftArray fs = new FailSoftArray(5);  
  
    // put some values in fs 
    for(int i=0; i < fs.Length; i++) 
      fs[i] = i;  
 
    // now index with ints and doubles 
    Console.WriteLine("fs[1]: " + fs[1]); 
    Console.WriteLine("fs[2]: " + fs[2]); 
 
    Console.WriteLine("fs[1.1]: " + fs[1.1]); 
    Console.WriteLine("fs[1.6]: " + fs[1.6]); 
 
  }  
}


Return class object from indexer

 
using System;
public class MyValue {
    public String Name;
}
class CardDeck {
    private MyValue[] Cards = new MyValue[52];
    public MyValue this[int index] {
        get {
            return Cards[index];
        }
        set {
            Cards[index] = value;
        }
    }
    public static void Main(String[] args) {
        try {
            CardDeck PokerDeck = new CardDeck();
            MyValue HiddenAce = PokerDeck[53];
        } catch (IndexOutOfRangeException e) {
            Console.WriteLine(e.Message);
        } finally {
            // Cleanup code
        }
    }
}


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


Use an indexer to create a fail-soft array

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Use an indexer to create a fail-soft array. 
 
using System; 
 
class FailSoftArray {  
  int[] a;    // reference to underlying array  
 
  public int Length; // Length is public 
 
  public bool errflag; // indicates outcome of last operation 
   
  // Construct array given its size. 
  public FailSoftArray(int size) { 
    a = new int[size]; 
    Length = size;  
  } 
 
  // This is the indexer for FailSoftArray. 
  public int this[int index] { 
    // This is the get accessor. 
    get { 
      if(ok(index)) { 
        errflag = false; 
        return a[index]; 
      } else { 
        errflag = true; 
        return 0; 
      } 
    } 
 
    // This is the set accessor 
    set { 
      if(ok(index)) { 
        a[index] = value; 
        errflag = false; 
      } 
      else errflag = true; 
    } 
  } 
 
  // Return true if index is within bounds. 
  private bool ok(int index) { 
   if(index >= 0 & index < Length) return true; 
   return false; 
  } 
}  
  
// Demonstrate the fail-soft array. 
public class FSDemo {  
  public static void Main() {  
    FailSoftArray fs = new FailSoftArray(5); 
    int x; 
 
    // show quiet failures 
    Console.WriteLine("Fail quietly."); 
    for(int i=0; i < (fs.Length * 2); i++) 
      fs[i] = i*10; 
 
    for(int i=0; i < (fs.Length * 2); i++) { 
      x = fs[i]; 
      if(x != -1) Console.Write(x + " "); 
    } 
    Console.WriteLine(); 
 
    // now, generate failures 
    Console.WriteLine("\nFail with error reports."); 
    for(int i=0; i < (fs.Length * 2); i++) { 
      fs[i] = i*10; 
      if(fs.errflag) 
        Console.WriteLine("fs[" + i + "] out-of-bounds"); 
    } 
 
    for(int i=0; i < (fs.Length * 2); i++) { 
      x = fs[i]; 
      if(!fs.errflag) Console.Write(x + " "); 
      else 
        Console.WriteLine("fs[" + i + "] out-of-bounds"); 
    } 
  } 
}