Ok, consider this common idiom that most of us have used many times (I assume):
class FooBarDictionary
{
private Dictionary fooBars;
... I've got a DefaultingDictionary<> which does about this. As a bonus
The extensions .AsDefaulting
can be used to transparently use any IDictionary<>
as a defaulting one, so you can opt to use any dictionary (even e.g. obtained from a thirdparty API) as a defaulting one, and the underlying container will be updated with any 'auto-vivified' items.
IDictionary dict = LoadFromDatabase();
// using a fixed value
SomeFunc(dict.AsDefaulting(defaultItem));
// using an independent generator function
var defaulting = dict.AsDefaulting(() => new MyItem { Id = System.Guid.NewGuid() });
// using a keydepedent generator function
var defaulting = dict.AsDefaulting(key => LazyLoadFromDatabase(key));
are included: