Home
Map
DictionaryEntry ExampleUse the DictionaryEntry struct with Hashtable. Loop over a HashTable with foreach.
C#
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.
Foreach
Type notes. 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.
KeyValuePair
Tuple
Foreach example. This example uses the Hashtable type and instantiates it upon the managed heap. Then 3 key-value pairs are added to the Hashtable instance.
Detail We use the foreach-loop construct to loop over the contents of the Hashtable instance.
Hashtable
Note This gives us a pair of values, encoded in a DictionaryEntry struct value.
struct
Also To access the key and value of a DictionaryEntry, please use the named properties.
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); } } }
3 = three 2 = two 1 = one
Class example. DictionaryEntry is not tied to the Hashtable collection. You can create an instance to store a key-value pair anywhere.
And Because this type is a value type, it is copied onto the evaluation stack whenever used as a variable or parameter.
Info The 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
A summary. To loop over a C# Hashtable collection, you can use the foreach-loop statement. Then access the properties on each DictionaryEntry.
Final note. 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.
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.