C# Source Code: Defining a custom indexer for a class
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Defining a custom indexer for a class
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, April 06, 2004
Hits:
588
Category:
General/Framework
Article:
The following code demonstrates how to use class indexers to access items of data within a class. using System; namespace vbUsers.Collections { class IndexedClassDemo { [STAThread] static void Main(string[] args) { //Indexer Example IndexedClass oIndexer = new IndexedClass(5); //Seed the storage space with 5 empty slots //Add a key/value pair oIndexer["andrew"]=31; Console.WriteLine("Current Value is " + oIndexer["andrew"]); //Update the key/value pair oIndexer["andrew"]=20; //Return the results Console.WriteLine("New Result is " + oIndexer["andrew"]); Console.ReadLine(); } } public class IndexedClass { public IndexedClass(int IntialSize) { //Size the internal array to store the key value pairs zoItems = new KeyItemPair[Math.Max(IntialSize,1)]; //Store the current no. of stored items ziLength = 0; } //Expose the Indexer public object this[string key] { get{ return (object)KeyToObject(key);} set{ AddToArray(key,value);} } //Returns the number of stored items public int Length() { return ziLength; } //Adds a key value pair to the internal array protected void AddToArray(string key, object item) { int ExistingKeyIndex = KeyPosition(key); if(ExistingKeyIndex > - 1) { //Key exists in array, update item zoItems[ExistingKeyIndex] = new KeyItemPair(key,item); } else { if(ziLength == zoItems.Length) { ResizeArray(); } zoItems[ziLength] = new KeyItemPair(key,item); ziLength++; } } //Increases the size of the array to store more items protected void ResizeArray() { ziLength += 5; KeyItemPair[] OldArray = zoItems; zoItems = new KeyItemPair[ziLength]; OldArray.CopyTo(zoItems,0); } //Returns the Object given the key protected object KeyToObject(string key) { for(int n = 0;n < ziLength;++n) { if(zoItems[n].key == key) { return zoItems[n].item; } } return null; } //Returns the position of the object within the internal array, given the key protected int KeyPosition(string key) { for(int Position = 0; Position < ziLength; ++Position) { if(zoItems[Position].key == key) { return Position; } } return -1; } //Value Type Structure to store key value pairs protected struct KeyItemPair { public KeyItemPair(string sKey, object oItem) { key = sKey ; item =oItem; } public object item; public string key; } protected KeyItemPair[] zoItems; protected int ziLength; } }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet