Like a Java's java.util.Hashtable, a .NET Hashtable is a useful data type which encapsulates key/value pairs.
Objects used as keys in a Hashtable must override or rely on the inherited GetHashCode and Equals methods of System.Object because these methods are invoked for matching. Note that the original Equals method in System.Object returns true only if both objects being compared are the same instance created on the heap. Hence, if key equality is simply reference equality, there is no need to override these methods.
The program below demonstrates how Hashtable can be used. The output is interspersed with the code to show the outputs of the different sections.
1: using System;
2: using System.Collections;
3:
4: public class TestClass{
5: public static void Main(){
6: // Using Add
7: Hashtable ht = new Hashtable();
8: ht.Add("A", "apple");
9: ht.Add("D", "durian");
10: ht.Add("B", "banana");
11: ht.Add("C", "coconut");
12: PrintCollection(ht);
13:
Output:
Key:C Value:coconut Key:A Value:apple Key:D Value:durian Key:B Value:banana
The static method PrintCollection is defined on line 43 below. It simply prints out all the key/value pairs in the Hashtable passed in.
14: // Using Count
15: Console.WriteLine("Count: " + ht.Count);
16:
Output:
Count: 4
17: // Using ContainsKey
18: Console.WriteLine(ht.ContainsKey("D"));
19: Console.WriteLine(ht.ContainsKey("S"));
20:
Output:
True False
21: // Using ContainsValue
22: Console.WriteLine(ht.ContainsValue("banana"));
23: Console.WriteLine(ht.ContainsValue("starfruit"));
24:
Output:
True False
25: // Using Remove (key)
26: Console.WriteLine("Removing key B...");
27: ht.Remove("B");
28: PrintCollection(ht);
29:
Output:
Removing key B... Key:C Value:coconut Key:A Value:apple Key:D Value:durian
30: // You can retrieve the keys using property Keys
31: Console.WriteLine("Looping through Keys...");
32: foreach (string key in ht.Keys){
33: Console.WriteLine(key);
34: }
35:
Output:
Looping through Keys... C A D
36: // You can retrieve the keys using public property
Values
37: Console.WriteLine("Looping through Values...");
38: foreach (string val in ht.Values){
39: Console.WriteLine(val);
40: }
41: }
42:
Output:
Looping through Values... coconut apple durian
43: // Prints out all the key-value pairs in the Hashtable 44: public static void PrintCollection (Hashtable h){ 45: IDictionaryEnumerator enumerator = h.GetEnumerator(); 46: 47: while ( enumerator.MoveNext() ) 48: Console.WriteLine("Key:" + enumerator.Key + 49: " Value:" + enumerator.Value); 50: 51: Console.WriteLine(); 52: } 53: }
18.118.12.50