stride3d/stride · error · KeyNotFoundException

The given key was not present in the dictionary.

Error message

The given key was not present in the dictionary.

What it means

The Fetch method (backing the indexer getter) throws KeyNotFoundException when the requested key does not exist in the HybridDictionary. In list mode it scans stored pairs and throws if no match is found; in dictionary mode the underlying Dictionary indexer throws the same message. This is standard read-miss semantics.

Solutions

  1. Use TryGetValue(key, out var value) instead of the indexer
  2. Check ContainsKey before reading
  3. Verify key spelling/casing against the comparer used at construction

Example fix

// before
var v = dict["missingKey"]; // throws
// after
if (dict.TryGetValue("missingKey", out var v)) { /* use v */ }
Defensive patterns

Strategy: try-catch

Validate before calling

if (dict.TryGetValue(key, out var value)) { /* use value */ }

Try / catch

try { var v = dict[key]; }
catch (KeyNotFoundException) { /* handle missing key */ }

Prevention

When it happens

Trigger: Reading `dict[key]` (or calling Fetch) with a key that was never added or was removed, in either list mode or dictionary mode.

Common situations: Typo'd or case-mismatched string keys with a case-sensitive comparer, reading before data is loaded, key removed by another part of the pipeline, races in multithreaded access.

Understand the failure class

Background: 'Could not be found', 'does not exist', 'not found in database': the resource-not-found family when an ID, slug, key, or URI lookup comes back empty — this error's family across 20 libraries.

Related errors


AI-assisted analysis of stride3d/stride@96fad776d2 (2026-09-14). Data as JSON: /api/errors/5694c0eb74cdfb7f. Report an issue: GitHub.

Appendix: source

Thrown at sources/core/Stride.Core.Design/Collections/HybridDictionary.cs:290

        CheckInvariant();
        return (IEnumerator<KeyValuePair<TKey, TValue>>?)list?.GetEnumerator() ?? dictionary!.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    private TValue Fetch(TKey key)
    {
        if (list != null)
        {
            foreach (var kvp in list)
            {
                if (keyComparer.Equals(kvp.Key, key))
                    return kvp.Value;
            }
            throw new KeyNotFoundException("The given key was not present in the dictionary.");
        }
        return dictionary![key];
    }

    private void Update(TKey key, TValue value)
    {
        valueCollection = null;
        if (list != null)
        {
            for (var i = 0; i < list.Count; i++)
            {
                var kvp = list[i];
                if (keyComparer.Equals(kvp.Key, key))
                {
                    list[i] = new KeyValuePair<TKey, TValue>(key, value);
                    return;
                }
            }

View on GitHub (pinned to 96fad776d2)