4.14 Creating Indexers

 <  Day Day Up  >  

You want to allow users of your class to use an indexer to retrieve individual elements from your collection.


Technique

Indexers allow users to access items within a class in the same way items within an array are accessed. To create an indexer for a custom collection class, rselect the class within ClassView that you want to add an indexer to and select Project, Add Indexer from the main menu. Select the data type from the Indexer Type field that is the data type of the value used to get or set an individual item in your collection, as shown shown in Figure 4.8. Next, add any parameters within the brackets of the indexer. Implement the get and set methods for the indexer within your class.

Figure 4.8. Add an indexer to your class by using the Add Indexer dialog.

graphics/04fig08.gif

Comments

Creating an indexer is similar to creating a regular class property. Like a property, it uses get and set procedures to manipulate an internal value within your class. Listing 4.9 shows an indexer for a class that allows you to change an individual digit within an integer. Although the class itself isn't a full .NET collection, it does serve to show how you can use an indexer to set an individual item within a collection.

Listing 4.9 Creating an Indexer
 using System; using System.Text; namespace _13_Indexers {     class Class1     {         [STAThread]         static void Main(string[] args)         {             IntegerString val = new IntegerString();             val.num = 12345;             for( int i = 0; i < 2; i++ )             {                 int swap;                 swap = val[i];                 val[i] = val[4-i];                 val[4-i] = swap;             }             Console.WriteLine( val.num );         }     }     class IntegerString     {         public int num = 0;         public int this[int index]         {             get             {                 return Int32.Parse(num.ToString()[index].ToString());             }             set             {                 StringBuilder sValue = new StringBuilder(num.ToString());                 sValue[index] = Char.Parse(value.ToString());                 num = Int32.Parse(sValue.ToString());             }         }     } } 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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