DictionaryEntry
This C# type is used with Hashtable
. The Hashtable
collection provides a way to access objects based on a key. We use DictionaryEntry
in a foreach
-loop.
Usually DictionaryEntry
is part of a foreach
-loop, but it can be used to store pairs together. This is similar to a KeyValuePair
or Tuple
.
This example uses the Hashtable
type and instantiates it upon the managed heap. Then 3 key-value pairs are added to the Hashtable
instance.
foreach
-loop construct to loop over the contents of the Hashtable
instance.DictionaryEntry
struct
value.DictionaryEntry
, please use the named properties.using System; using System.Collections; // 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); }3 = three 2 = two 1 = one
Class
exampleDictionaryEntry
is not tied to the Hashtable
collection. You can create an instance to store a key-value pair anywhere.
DictionaryEntry
struct
stores 2 object references. Each object reference is 8 bytes on 64-bit systems.using System; using System.Collections; class Program { static DictionaryEntry GetData() { // Return DictionaryEntry as key-value pair. return new DictionaryEntry("cat", "frog"); } static void Main() { var data = GetData(); Console.WriteLine(data.Key); Console.WriteLine(data.Value); } }cat frog
To loop over a C# Hashtable
collection, you can use the foreach
-loop statement. Then access the properties on each DictionaryEntry
.
The DictionaryEntry
struct
is not a class
, and is stored on the stack when used as a local variable. It can be instantiated anywhere in C# programs.