Working with HashTable in C# 2.0

This is a 3 part tutorial on the Hashtable class available in .NET 2.0. Part one is here and soon you will get access to the other two parts. There might be some brainstorming sessions in the last one. Please download the attached code to see the working sample.
First of all Why Hashtable? The answer is very simple. Suppose you have some data that needs to be stored in a two-dimensional array and have a link format of Key and Value. For example, a person name and his social security number and we can access the data using a key.
A close friend of Hashtable is Array (as from C/C++), it is an instance of the System.Array class, but to access data from an array you must have an index and that is of int Type. And second you must specify the size of the Array at the time of instantiations.
Family contains
  • ArrayList
  • Collection
  • Dictionary (Hashtable or Maps)

Dictionaries or Hashtable

Are very sophisticated data structures that allow access to an element based on some key, that can be of any type.

Hashtable in .Net

Is a member of the System.Collections namespace.
Contains 15 constructors ( wow, try them all) but you will mostly use.
  1. Hashtable _table = new Hashtable(); //Default one  
  2. Hashtable _table2 = new Hashtable(10); // capacity or size.  
  3. Hashtable _table3 = new Hashtable(10, 06); //capacity , loadfactor  
Loadfactor: this factor helps a lot if you are looking for performance. The smaller the load size (fraction of the hashtable full .6 means 60% full), the more efficiently our hash table works and the more memory it occupies.
Now for some code:
  1. Create a Hashtable
    1. Hashtable _simpleTable = new Hashtable();  
  2. Add some data in it.
    1. _simpleTable.Add("Key1""Value1");  
    2. _simpleTable.Add("Key2""Value2");  
  3. Get the size.
    1. _simpleTable.Count; // an int value.  
  4. Now to fetch data
  5. Create an object of "IDictonaryEnumerator", this is an interface that creates an enumerator and customized for "Dictonary" objects.
    1. IDictionaryEnumerator _enumerator = _simpleTable.GetEnumerator();  
    2. while (_enumerator.MoveNext())  
    3. {  
    4.     _string += _enumerator.Key + " ";  
    5.     _string += _enumerator.Value + "\n";  
    6. }
  6. And that is all you do to fetch the data!!!
  7. Clear the hash table:
    1. _simpleTable.Clear();
  8. Search for a specific key: remember its value type when used
    1. if (_simpleTable.ContainsKey("Key1"))  
    2. {  
    3.     Console.WriteLine("Key1 is present");  
    4. }
  9. Search for a specific key: remember its value type when used
    1. if (_simpleTable.ContainsValue("Value1"))  
    2. {  
    3.     Console.WriteLine("Value1 is present");  
    4. }
Have all this done and you will get more stuff in the next article.
Try this and Cheers!!!!!

Similar Articles