Boost Your .NET Projects with Spargine: Simplify Dictionary Handling with AutoDefaultDictionary

Spargine is a collection of open-source assemblies and NuGet packages designed for .NET 10, which I have been developing and maintaining since the release of .NET Framework 2. These assemblies are not only a core part of my projects but are also actively deployed in production environments across several companies I collaborate with.

Get Spargine

You can access the source code and NuGet packages here:

The AutoDefaultDictionary<TKey, TValue> class in the DotNetTips.Spargine.Core assembly and NuGet package, simplifies working with dictionaries by automatically returning a default value (or generating one dynamically) when a key is missing. Instead of throwing exceptions or forcing you to write repetitive lookup code, missing keys are handled gracefully — making your code cleaner and more resilient.

This type was inspired by an insightful article written by Simon Painter, which sparked my interest in implementing the concept as part of Spargine.

Why Use AutoDefaultDictionary?

In many applications, missing data is expected — and your code shouldn’t break because of it. With AutoDefaultDictionary, you can:

  • Return a static default value
  • Or generate values dynamically using a factory function
  • Optionally store the generated value in the dictionary
  • Avoid KeyNotFoundException
  • Reduce boilerplate lookup logic

Usage Example

var dictionary = new AutoDefaultDictionary<string, Coordinate>(coordinates, defaultCoordinate);

var result = dictionary["notincollection"];

In this example, the key “notincollection” does not exist.
Instead of throwing an exception, the configured defaultCoordinate object is returned automatically.

Constructors

The following constructors give you full control over how missing keys are handled:

  • AutoDefaultDictionary()
    Initializes a new instance with a default value.
  • AutoDefaultDictionary(Func<TKey, TValue> onMissingKey)
    Uses a function to dynamically generate values for missing keys.
  • AutoDefaultDictionary(Func<TKey, TValue> onMissingKey, IEqualityComparer<TKey> comparer)
    Uses a factory function with a custom comparer.
  • AutoDefaultDictionary(IDictionary<TKey, TValue> dictionary, Func<TKey, TValue> onMissingKey)
    Applies a dynamic factory to an existing dictionary.
  • AutoDefaultDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue)
    Applies a static default value to an existing dictionary.
  • AutoDefaultDictionary(IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, TValue defaultValue)
    Initializes from key/value pairs with a static default value.
  • AutoDefaultDictionary(IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, Func<TKey, TValue> onMissingKey)
    Initializes from key/value pairs with a factory function.
  • AutoDefaultDictionary(IEqualityComparer<TKey> comparer)
    Initializes using a custom comparer.
  • AutoDefaultDictionary(in Func<TKey, TValue> onMissingKey, int capacity)
    Initializes with a factory function and initial capacity.
  • AutoDefaultDictionary(TValue defaultValue)
    Initializes with a static default value.
  • AutoDefaultDictionary(TValue defaultValue, IEqualityComparer<TKey> comparer)
    Uses a static default value with a comparer.
  • AutoDefaultDictionary(TValue defaultValue, int capacity)
    Initializes with a static default value and initial capacity.

Key Methods

  • AddOrUpdate(…)
    Adds a value or updates an existing one using a factory delegate.
  • Clear()
    Removes all keys while retaining default-value behavior.
  • ContainsValue(…)
    Determines whether the dictionary contains a specific value.
  • GetOrAdd(key, factory)
    Returns the value for a key or creates and stores it using the factory.
  • GetOrAdd(key, value)
    Returns the value for a key or stores the provided value.
  • GetValueOrDefault(key)
    Returns the value or the configured default — without adding it to the dictionary.
  • ToImmutableDictionary()
    Creates an immutable snapshot.
  • ToReadOnlyDictionary()
    Returns a read-only wrapper.
  • TryAdd(key, value)
    Attempts to add a value.
  • TryUpdate(key, newValue, comparisonValue)
    Updates a value only if the existing value matches.

Indexer Behavior

public new TValue this[TKey key]

Retrieves or sets the value for the given key.
If the key does not exist:

  • The default value (or factory-generated value) is returned
  • And it is automatically added to the dictionary

Properties

  • DefaultValue
    Returns the default value used when a key is missing.
  • OnMissingKeyFactory
    Returns the factory function used to generate missing values, or null if a static default value is being used.

sUMMARY

Spargine continues to evolve to meet real-world developer needs. If you have suggestions or feature requests for improving AutoDefaultDictionary, I’d love to hear from you!

A special thanks to James Curran for suggesting the use of a function-based default value — an idea that made this type even more powerful.

Get Involved!

The success of open-source projects like Spargine relies on community contributions. If you find these updates useful or have ideas for further improvements, I encourage you to contribute by:

  • Submitting pull requests
  • Reporting issues
  • Suggesting new features

Your input is invaluable in making Spargine an even more powerful tool for the .NET community.

If you are interested in contributing or have any questions, feel free to contact me via email at dotnetdave@live.com. Your support and collaboration are greatly appreciated!

Thank you, and happy coding!

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.