Skip to content

ImmutableArray<T>.Builder.InsertRange returns unexpected values when it use the same instance #136026

Description

@prozolic

Description

When it use the same Builder with ImmutableArray<T>.Builder.InsertRange, the resulting values differ from the expected value.
For example, using the same instance on a ImmutableArray<T>.Builder whose elements are set to [1, 2, 3] and execute InsertRange(1, builder), the result is [1, 1, 1, 1, 2, 3] instead of [1, 1, 2, 3, 2, 3].

Reproduction Steps

ImmutableArray<int> array = Enumerable.Range(1,3).ToImmutableArray();
ImmutableArray<int>.Builder builder = array.ToBuilder();
builder.InsertRange(1, builder);
var result = builder.ToImmutable();

foreach (var item in result)
{
    Console.WriteLine(item); // [1,1,1,1,2,3] (Should return [1,1,2,3,2,3])
}

Expected behavior

The contents of the builder before the call are inserted at the specified index, the same as List<T>.InsertRange(1, list).

Actual behavior

The first element is inserted repeatedly.

Regression?

No response

Known Workarounds

No response

Configuration

I have confirmed this in .NET 8+.

Other information

The problem is in the fallback path of ImmutableArray<T>.Builder.InsertRange(int, IEnumerable<T>):

// ImmutableArray<T>.Builder.InsertRange.cs
if (index != this.Count)
{
    Array.Copy(_elements, index, _elements, index + count, _count - index);
}

if (!items.TryCopyTo(_elements, index))
{
    foreach (T item in items)          // items == this
    {
        _elements[index++] = item;     // overwrites elements that are read later
    }
}

This will be fixed by #125304, which changes ImmutableExtensions.TryCopyTo to use ICollection<T>.CopyTo for all ICollection<T> implementations instead of only well-known types. ImmutableArray<T>.Builder.CopyTo(T[], int) is implemented with Array.Copy(_elements, 0, array, index, Count), and Array.Copy handles overlapping source/destination ranges correctly, so the result becomes the expected [1, 1, 2, 3, 2, 3].

Activity

  1. added
    untriaged
    on Oct 18, 2026
  2. dotnet-policy-service commented on Oct 18, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-collections
    See info in area-owners.md if you want to be subscribed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

area-System.Collectionsuntriaged

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions