Thursday, May 05, 2005

Indexers in .NET

How can we write a customCollection object which behaves the same way as a ASP.NET session object or Application object, i.e. retrieve the values using indexes.

For e.g. we can retrieve a object from Session as :
object obj = Session["key"]; //to retrieve
Session["key"] = obj; //add or set a value in Session.

Writing our own Collection object which behaves in a similar manner is very simple, using Indexes in C #See code below:

class MyCollection
{
private Hashtable hashTable = new Hashtable();
public object this [object index]
{
get{return hashTable[index];} set{hashTable[index] = value;}
}
}

Now we can use MyCollection object as shown below:

MyCollection myCollection = new MyCollection();
myCollection["Naren"] = "Swetha";
Console.WriteLine("value >> " + myCollection["Naren"]);

That's it....

No comments:

Post a Comment