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.
HybridDictionary
is used in the same way as Hashtable
. The HybridDictionary
type is found in the System.Collections.Specialized
namespace.
GetHybridDictionary
method a HybridDictionary
is allocated—it is populated with some key-value pairs.string
parameter indexer. This behavior is like that of Hashtable
.string
indexer. We can assign an object, which aliases System.Object
type.HybridDictionary
. The Key and Value are objects.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
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
.
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.