Use Customized Indexers


Many of you are aware of indexers and its properties. For those unaware of it want to know that indexers are used to represent objects using indexes or even using keys. i.e. we can represent an object of a class by the way an array is using. But this is the default behavior of an indexer i.e. its return type is an integer and indexed objects are representing using integer type indexes. But we can override theses default items, as return type may be an object and representing indexed objects using string type keys rather than integer type indexes. I tried to explain here with some sort of coding.

Start a new C# web project in VS.NET and add a class Nations to it. Click the ClassView button, as any thing you want to add in a class type is very easy in VS.NET by making the class view of the project and just right click on that particular class. So after right click the class select add -> add indexer menu and your default indexer will added to the class. But change the definition of that indexer like below.

/// <summary>

/// Overrides the default indexer prototype

/// </summary>

public Nations this[string nationName]

{

          get

          {

                   return (Nations)nationsObjects[nationName]; 

          }

          set

          {

                    if (nationsObjects.Contains(nationName))

                   {

                             nationsObjects.Remove(nationName);

                   }

                   nationsObjects.Add(nationName,(Nations) value); 

          }

}

Basically I changed the return type of the indexer to "Nation" type and changed the default integer type indexes to a string type key. So now indexer will active by the statement <object>[<key>] compare to the previous status of <object>[<index>]. Each indexed objects want to be stored and will use later and more over this storing want to be performed using a string type key value. For that we want a ListDictionary in to which all indexed objects will keep. The statement nationsObjects.Add(nationName,(Nations) value); is used for this stored precess and the (Nations)nationsObjects[nationName]; statement in side the get will return a particular indexed object on the basis of a key value. Ok this is the main activities in the class.

In the front end I first create a normal object using the statement Nations n = new Nations(); and then the real thing happens.  Look this statement n["india"] = new Nations(); got it? Nothing here I indexed the object "n" using a key "india" and assign it to a type of Nations. Now you can use n ["india"] like any other object to access the resources of the type Nations. The difference is that we can represent this particular object with a key ("india"). In this way you can create more objects with different keys and perform various operations. Look at the sample code along with this article, as you may get clearer picture on customized indexers.


Similar Articles