dotnet/wpf · error · NotSupportedException

throw new NotSupportedException();

Error message

throw new NotSupportedException();

What it means

SequentialUshortCollection implements ICollection<ushort> as a read-only, run-length-encoded collection, so Remove(ushort) is not a supported operation and always throws NotSupportedException. Mutating this collection is impossible by design.

Solutions

  1. Do not mutate the collection; build a new List<ushort> from it and edit that
  2. Check the IsReadOnly property (returns true) before mutating
  3. Copy items into your own collection type if modification is required
  4. Cast defensively: if collection.IsReadOnly, skip remove logic

Example fix

// before
ushortCollection.Remove(5);
// after
var editable = new List<ushort>(ushortCollection);
editable.Remove(5);
Defensive patterns

Strategy: type-guard

Validate before calling

static bool CanRemove(ICollection<ushort> c) => !c.IsReadOnly;

Type guard

static List<ushort> AsEditable(IEnumerable<ushort> src) => new List<ushort>(src);

Try / catch

try { c.Remove(item); }
catch (NotSupportedException) { /* collection is read-only: copy and edit */ }

Prevention

When it happens

Trigger: Calling Remove(item), or LINQ/`List.Remove`-style mutation paths (e.g. ICollection<ushort>.Remove via interface) on a SequentialUshortCollection obtained from WPF (e.g. structure related to TextSource/character runs).

Common situations: Attempting to edit a collection that the API hands out as read-only; generic code that assumes any ICollection<T> is mutable.

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 dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/6f6fcae6b4ad5995. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/Shared/MS/Internal/SequentialUshortCollection.cs:66

            ArgumentOutOfRangeException.ThrowIfGreaterThan(arrayIndex, array.Length - Count);

            for (ushort i = 0; i < _count; ++i)
                array[arrayIndex + i] = i;
        }

        public int Count
        {
            get { return _count; }
        }

        public bool IsReadOnly
        {
            get { return true; }
        }

        public bool Remove(ushort item)
        {
            throw new NotSupportedException();
        }

        #endregion

        #region IEnumerable<ushort> Members

        public IEnumerator<ushort> GetEnumerator()
        {
            for (ushort i = 0; i < _count; ++i)
                yield return i;
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {

View on GitHub (pinned to 81131a70a4)