stride3d/stride · error · NotSupportedException

attempt to modify a key

Error message

attempt to modify a key

What it means

The key list returned by SortedList.Keys is a read-only view; its indexer setter throws NotSupportedException with 'attempt to modify a key' because changing a key in place would break the sorted-order invariant of the list.

Solutions

  1. Remove the old entry and add the corrected one: sortedList.RemoveAt(i); sortedList[newKey] = value;
  2. Treat Keys as read-only; mutate entries only through the SortedList itself
  3. If bulk key updates are needed, rebuild the SortedList from corrected pairs

Example fix

// before
sortedList.Keys[i] = newKey; // throws
// after
var value = sortedList.Values[i];
sortedList.RemoveAt(i);
sortedList[newKey] = value;
Defensive patterns

Strategy: validation

Validate before calling

bool isReadOnlyKeyView(IList<TKey> keys) => keys is System.Collections.IList l && l.IsReadOnly;

Type guard

static bool IsReadOnlyKeyView<TK,TV>(SortedList<TK,TV> list, IList<TK> view) => view == list.Keys;

Try / catch

try { keysView[i] = newKey; } catch (NotSupportedException) { var v = list.Values[i]; list.RemoveAt(i); list[newKey] = v; }

Prevention

When it happens

Trigger: Assigning through the key view's indexer, e.g. sortedList.Keys[i] = newKey, or via the IList interface cast.

Common situations: Trying to 'fix' a wrong key in place; code ported from a mutable IList<TKey> usage; misunderstanding that Keys is a live read-only projection.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


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

Appendix: source

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

        public virtual void Insert(int index, TKey item)
        {
            throw new NotSupportedException();
        }

        public virtual void RemoveAt(int index)
        {
            throw new NotSupportedException();
        }

        public virtual TKey this[int index]
        {
            get
            {
                return host.KeyAt(index);
            }
            set
            {
                throw new NotSupportedException("attempt to modify a key");
            }
        }

        //
        // IEnumerable<TKey>
        //

        public virtual IEnumerator<TKey> GetEnumerator()
        {
            /* We couldn't use yield as it does not support Reset () */
            return new KeyEnumerator(host);
        }

        //
        // ICollection
        //

        public virtual int Count => host.Count;

View on GitHub (pinned to 96fad776d2)