Skip to content

Incorrect loop bound in SizeOptIListSelectIterator.ToList #137126

Description

@equmagg

Description

SizeOptIListSelectIterator<TSource, TResult>.ToList() checks the destination list’s Count immediately after constructing it with a capacity. Since Count is zero, the loop never executes and the override returns an empty list for a nonempty source.

Admittedly, this path is non-public and functionally dead, but it hides a ticking time bomb, so would be nice to fix for good hygiene (or remove altogether)

Reproduction Steps

With true

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

IEnumerable<int> query = new[] { 1, 2, 3 }.Select(x => x * 10);

MethodInfo method = query.GetType().GetMethod(
    "ToList",
    BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
    ?? throw new InvalidOperationException("ToList override not found");

List<int> result = (List<int>)(method.Invoke(query, null)
    ?? throw new InvalidOperationException("ToList returned null"));

Console.WriteLine(query.GetType().Name);
Console.WriteLine($"Reflection: [{string.Join(", ", result)}]");
Console.WriteLine($"Public API: [{string.Join(", ", query.ToList())}]");

Expected behavior

printing [10, 20, 30], matching enumeration of the query

Actual behavior

prints []

Regression?

The erroneous loop was included when this iterator was introduced in #118156

Known Workarounds

No workaround is needed

Configuration

Windows 10, x64
Reproduced on .NET 10, 11 rc3 and main

Other information

List<TResult> list = new List<TResult>(_source.Count);
for (int i = 0; i < list.Count; i++)
{
    list.Add(_selector(_source[i]));
}
return list;

The constructor initializes Capacity, not Count

Activity

  1. dotnet-policy-service commented on Nov 7, 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

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions