Home
C#
DictionaryEntry Example
Updated Oct 11, 2023
Dot Net Perls
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.
Start We use the foreach-loop construct to loop over the contents of the Hashtable instance.
Hashtable
And The loop 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; // 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 11, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen