C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
The Hashtable collection provides a way to access objects based on a key. But it does not implement advanced logic for iterating over the contents. We use DictionaryEntry in a foreach-loop.
Example. This example uses the Hashtable type and instantiates it upon the managed heap. Then, three key-value pairs are added to the instance. Third, we use the foreach-loop construct to loop over the contents of the Hashtable instance.
Note: This gives us a pair of values, encoded in a DictionaryEntry struct value.
Also: To access the key and value of a DictionaryEntry, please use the named properties.
C# program that uses DictionaryEntry type and foreach using System; using System.Collections; class Program { static void Main() { // Create hashtable with some keys and values. Hashtable hashtable = new Hashtable(); hashtable.Add(1, "one"); hashtable.Add(2, "two"); hashtable.Add(3, "three"); // Enumerate the hashtable. foreach (DictionaryEntry entry in hashtable) { Console.WriteLine("{0} = {1}", entry.Key, entry.Value); } } } Output 3 = three 2 = two 1 = one
Discussion. DictionaryEntry is not tied to the Hashtable collection. You can create an instance to store a key-value pair anywhere. Because this type is a value type, it is copied onto the evaluation stack whenever used as a variable or parameter.
And: The DictionaryEntry stores two object pointers, which are four bytes on 32-bit operating systems but eight bytes on 64-bit systems.
Summary. To loop over a Hashtable collection, then, you can use a foreach-loop construct and then access the properties on each DictionaryEntry. As with many associative collections, the looping order is undefined.
Value type: The DictionaryEntry type, as a value type, does not incur the overhead of objects.
Further: It can be instantiated anywhere in your program to store a pair of object references.