stride3d/stride · error · ArgumentException

element already exists

Error message

element already exists

What it means

PutImpl is the internal insert routine used by the constructor and Add(). When the binary search finds the key already present (freeIndx >= 0) and the overwrite flag is false, Add throws ArgumentException("element already exists") because SortedList requires unique keys. This is the duplicate-key case of adding to a sorted collection.

Solutions

  1. Use the indexer sortedList[key] = value to upsert (insert or overwrite).
  2. Check ContainsKey(key) (or IndexOfKey(key) < 0) before calling Add.
  3. Deduplicate the source data before populating the SortedList.
  4. Remove the existing key first if replacement is intended.

Example fix

// before
sortedList.Add("timeout", 30); // throws if exists
// after
sortedList["timeout"] = 30; // upsert
Defensive patterns

Strategy: validation

Validate before calling

if (sortedList.ContainsKey(key))
    sortedList[key] = value;
else
    sortedList.Add(key, value);

Type guard

static bool IsNewKey<TKey,TValue>(System.Collections.Generic.SortedList<TKey,TValue> list, TKey key) =>
    !list.ContainsKey(key);

Try / catch

try { sortedList.Add(key, value); }
catch (ArgumentException ex) when (ex.Message == "element already exists")
{ sortedList[key] = value; }

Prevention

When it happens

Trigger: sortedList.Add(existingKey, someValue); building a SortedList from data with duplicate keys (e.g. a config file or CSV with repeated keys); re-running an initialization routine that re-adds the same keys.

Common situations: Loading key/value pairs from unordered or duplicated external data; double initialization of a lookup table; merging two collections that share keys.

Related errors


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

Appendix: source

Thrown at sources/core/Stride.Core/Collections/SortedList.cs:538

        ArgumentNullException.ThrowIfNull(key);

        var table = this.table;

        var freeIndx = -1;

        try
        {
            freeIndx = Find(key);
        }
        catch (Exception)
        {
            throw new InvalidOperationException();
        }

        if (freeIndx >= 0)
        {
            if (!overwrite)
                throw new ArgumentException("element already exists");

            table[freeIndx] = new KeyValuePair<TKey, TValue>(key, value);
            ++modificationCount;
            return;
        }

        freeIndx = ~freeIndx;

        if (freeIndx > Capacity + 1)
            throw new Exception("SortedList::internal error (" + key + ", " + value + ") at [" + freeIndx + "]");


        EnsureCapacity(Count + 1, freeIndx);

        table = this.table;
        table[freeIndx] = new KeyValuePair<TKey, TValue>(key, value);

        ++inUse;

View on GitHub (pinned to 96fad776d2)