Home
Map
HybridDictionary ExampleUse HybridDictionary and learn about how it changes its internal representation.
C#
This page was last reviewed on Jun 21, 2023.
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.
Cast
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 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.
This page was last updated on Jun 21, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.