stride3d/stride · error · InvalidOperationException

Cannot call SetItem on a SortedObservableCollection

Error message

Cannot call SetItem on a SortedObservableCollection

What it means

SortedObservableCollection positions items by its comparer, so replacing an item in place via SetItem could break the sort invariant. SetItem is overridden to always throw InvalidOperationException. Mutate the item or remove/re-add it instead.

Solutions

  1. Remove the old item and Insert/SortAdd the new one so the comparer places it correctly
  2. Mutate the existing item if it implements INotifyPropertyChanged so re-sorting hooks can react
  3. Use a plain ObservableCollection if index-based replacement is required

Example fix

// before
sortedCollection[i] = newItem;
// after
sortedCollection.RemoveAt(i);
sortedCollection.Add(newItem); // inserted in sorted position
Defensive patterns

Strategy: validation

Validate before calling

if (collection is SortedObservableCollection<T>) { collection.RemoveAt(index); collection.Add(newItem); } else collection[index] = newItem;

Type guard

bool SupportsSetItem(object c) => c is not SortedObservableCollection<T>;

Try / catch

try { collection[index] = newItem; } catch (InvalidOperationException) { collection.RemoveAt(index); collection.Add(newItem); }

Prevention

When it happens

Trigger: Calling the collection indexer setter, e.g. collection[i] = newItem, or any API that internally calls SetItem on a SortedObservableCollection.

Common situations: Updating an element's value in-place assuming ObservableCollection semantics; MVVM code assigning selected items by index.

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/9259a42be6bc1b24. Report an issue: GitHub.

Appendix: source

Thrown at sources/presentation/Stride.Core.Presentation/Collections/SortedObservableCollection.cs:171

        int i = GetIndex(item, true);
        base.InsertItem(i, item);
    }

    /// <inheritdoc/>
    protected override void MoveItem(int oldIndex, int newIndex)
    {
        throw new InvalidOperationException("Cannot call MoveItem on a SortedObservableCollection");
    }

    protected void ObservableCollectionMoveItem(int oldIndex, int newIndex)
    {
        base.MoveItem(oldIndex, newIndex);
    }

    /// <inheritdoc/>
    protected override void SetItem(int index, T item)
    {
        throw new InvalidOperationException("Cannot call SetItem on a SortedObservableCollection");
    }
}

View on GitHub (pinned to 96fad776d2)