Skip to content

LazyDictionary

kobi2294 edited this page Apr 18, 2019 · 1 revision

Lazy Dictionary Class

A class that implements the IDictionary<K, T> interface, but when the user tries to access an item that does not exist, uses a predefined factory to genrate it. It also waits with the memory allocation of the entire collection till the user accesses the first item.

Constructor

        public LazyDictionary(Func<TKey, TValue> factory)

You need to supply a factory function, that takes a key and returns a value. This function will be used to generate items that do not yet exist.

Example

            var ld = new LazyDictionary<string, ConsoleColor>(s => s.ParseEnum<ConsoleColor>());
            Console.WriteLine($"There are {ld.Count} Items"); // There are 0 items

            var cred = ld["Red"];

            Console.WriteLine($"cred: {cred}");    // cred: Red

            ld["Red"] = ConsoleColor.DarkRed;
            cred = ld["White"];

            Console.WriteLine($"There are {ld.Count} Items"); // There are 2 items

            // Key: Red, Value: DarkRed
            // Key: White, Value: White
            foreach (var pair in ld)    
            {
                Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
            }
Clone this wiki locally