C# DictionaryEntry Type

Hashtable type

The Hashtable collection in the C# language and .NET Framework provides a way to access objects based on a key quickly. But the Hashtable does not implement advanced logic for iterating over the contents. You can instead use the DictionaryEntry type in a foreach loop construct.

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—this gives us a pair of values, encoded in a DictionaryEntry value. To access the key and value of a DictionaryEntry, please use the named properties.

This C# example program uses the DictionaryEntry struct with Hashtable.

Program that uses DictionaryEntry type and foreach [C#]

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

Further DictionaryEntry uses

Programming tip

The DictionaryEntry type is not actually tied to the Hashtable collection in any way. You can create an instance of the DictionaryEntry to store a key-value pair anywhere you want to. Because this type is a value type, it will be copied onto the evaluation stack whenever it is used as a local variable or method parameter. The DictionaryEntry stores two object pointers, which are four bytes on 32-bit operating systems but eight bytes on 64-bit operating 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. 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.

Collections
.NET