Home
C#
HybridDictionary Example
Updated Jun 21, 2023
Dot Net Perls
HybridDictionary. This C# collection attempts to optimize Hashtable. It switches from a linked list to a hash table when the number of elements increases past a certain threshold.
When you have a small number of elements, using an array can be faster to search. Computing the hash code takes longer than looping and testing each element.
An example. HybridDictionary is used in the same way as Hashtable. The HybridDictionary type is found in the System.Collections.Specialized namespace.
DictionaryEntry
Note In GetHybridDictionary method a HybridDictionary is allocated—it is populated with some key-value pairs.
Start We can use the Add method or assign new entries with the string parameter indexer. This behavior is like that of Hashtable.
Hashtable
Info We can access the values by using the string indexer. We can assign an object, which aliases System.Object type.
object
Next After we acquire the object, we must cast the reference or value type. This impacts performance.
Finally The console application loops through the HybridDictionary. The Key and Value are objects.
foreach
using System; using System.Collections; using System.Collections.Specialized; class Program { static HybridDictionary GetHybridDictionary() { // Get and return HybridDictionary. HybridDictionary hybrid = new HybridDictionary(); hybrid.Add("cat", 1); hybrid.Add("dog", 2); hybrid["rat"] = 0; return hybrid; } static void Main() { HybridDictionary hybrid = GetHybridDictionary(); // Get values from HybridDictionary. int value1 = (int)hybrid["cat"]; object value2 = hybrid["???"]; object value3 = hybrid["dog"]; int count1 = hybrid.Count; // Display values. Console.WriteLine(value1); Console.WriteLine(value2 == null); Console.WriteLine(value3); Console.WriteLine(count1); // Enumerate HybridDictionary. foreach (DictionaryEntry entry in hybrid) { Console.Write(entry.Key); Console.Write(": "); Console.WriteLine(entry.Value); } } }
1 True 2 3 cat: 1 dog: 2 rat: 0
Generics. There is no collection that has the same change-over logic in the System.Collections.Generic namespace. Usually programs are better served with just a Dictionary.
Dictionary
We used HybridDictionary from System.Collections.Specialized. This C# type helps with small collections. But it is slower in many cases due to its internal logic.
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 Jun 21, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen