C Indexers


C# Indexers

If you read Chapter 26, which covers array properties in Delphi, you already know almost everything about C# indexers — they are a C# language construct that allows you to access classes and records as if they were arrays.

To declare an indexer, you have to use the following syntax:

public ReturnType this[Type Identifier] /* for instance */ public string this[int index]

Listing 30-11 shows a simple Languages class that contains a private string array and allows access to the array through two indexers. One indexer accepts an integer value and returns the string at the specified index. The other indexer accepts a string and returns the index of the string if it exists in the array.

Listing 30-11: C# indexers

image from book
using System; namespace Wordware.Indexers {    class Languages    {       private string[] langArray = {"Delphi", "<empty>", "C++",         "IL", "Assembler", "JScript.NET", "VB.NET" };       public string this[int index]       {         get {            // index is available in get and set blocks            if(index >= 0 && index <= langArray.Length - 1)               return langArray[index];            else               throw new IndexOutOfRangeException();         }         set {            // value is only available in the set block            if(index < 0)               langArray[0] = value;            else if(index > langArray.Length - 1)               langArray[langArray.Length - 1] = value;            else               langArray[index] = value;         }       }       /* return the index of a language, read-only */       public int this[string index]       {         get {            for(int cnt=0; cnt<langArray.Length - 1; cnt++)            {               if(langArray[cnt] == index)                  return cnt;            }            // if not found return -1            return -1;         }       }    }    class IndexersUser    {        [STAThread]       static void Main(string[] args)       {         Languages lg = new Languages();         try         {            // display Delphi            Console.WriteLine(lg[0]);            // find the "<empty>" item and replace it with "C#"            int empty = lg["<empty>"];            if(empty != -1)            {               lg[empty] = "C#";               Console.WriteLine(lg[empty]);            }            // throw the invalid index exception            Console.WriteLine(lg[-1]);         }         catch(Exception e)         {            Console.WriteLine();            Console.WriteLine("Exception thrown by the indexer:");            Console.WriteLine(e.ToString());         }         Console.ReadLine();       }    } }
image from book



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net