Pages

2012-04-04

DOTNET: Implementing a Custom Indexer

So you need to be able to access data in your custom type like an array?


You can enable array-style indexing for you class by implementing a custom indexer. A custom indexer
is like a property, but the name of the property is the keyword this. You can choose any type to be used
as the index and any type to return as the result.


public class TelephoneItem
{
    ArrayList _number = 
new ArrayList();

   
public TelephoneItem()
   {
      
//SomeConstructor  }
   
public void Add(string PhoneNumber)
   {
       _number.Add(PhoneNumber);
   }
   
public object this [int idx]
   {
      
get     {
         
if(_number.Count < idx)<BR>          {
            
return _number[idx];
         }
         
else        {
            
throw new IndexOutOfRangeException("[TelephoneItem.get_Item]" +
                "Index Out of Range");
         }  
      }
      
set     {
         
if(_number.Count < idx)<BR>          {
             _number[idx] = 
value;
         }
         
else        {
            
throw new IndexOutOfRangeException("[TelephoneItem.set_Item]" +
                "Index Out of Range");
         }
           }        
   }
}