Saturday, August 25, 2007

HashTable > Basics and Code Listing

HASHTABLE
• Hashtable maintains two object arrays, onefor keys and other for values
• When a Key-Value pair is inserted in Hashtable, it automatically tracks which key belongs to which value
• A Hashtable cannot contain duplicate keys, if Add method is called with a key already present, it will cause an excpetion
• Key’s presence can be tested by using ContainsKey method
• Using foreach to iterate a Hashtable returns a DictionaryEntry
• DictionaryEntry provides access to Key and Value elements
• Sample code as under:

using System;
using System.Collections;

Hashtable ages = new Hashtable();

ages[“John”] = 42;
ages[“Kathy”]=23;
ages[“Mary”]=12;

foreach(DictionaryElement in ages)
{
string name = (string)element.key;
int age = (int)element.key;
}

No comments: