Skip to content

Enumerable.Concat() method throws an ArgumentOutOfRangeException if it is called after a Skip() #123284

@pelmenin

Description

@pelmenin

Description

Enumerable.Concat() method throws an ArgumentOutOfRangeException if it is called after a Skip() method that has skipped more elements than exist.

Reproduction Steps

Program.cs:

using System.Linq;

var source = new int[] { 1 };
var items = new int[] { 2, 3 };

var result = source
    .Skip(2)
    .Concat(items)
    .ToArray();

csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

Expected behavior

result = [ 2, 3 ]

Actual behavior

A ArgumentOutOfRangeException is thrown:

System.ArgumentOutOfRangeException
  HResult=0x80131502
  Message=Specified argument was out of the range of valid values.
  Source=System.Private.CoreLib
  StackTrace:
   at System.ThrowHelper.ThrowArgumentOutOfRangeException()
   at System.ReadOnlySpan`1.Slice(Int32 start, Int32 length)
   at System.Linq.Enumerable.IListSkipTakeIterator`1.Fill(IList`1 source, Span`1 destination, Int32 sourceIndex)
   at System.Linq.Enumerable.IListSkipTakeIterator`1.CopyTo(TSource[] array, Int32 arrayIndex)
   at System.Linq.Enumerable.Concat2Iterator`1.ToArray()
   at Program.<Main>$(String[] args) in C:\Work\Projects\Tests\EnumerableIssue\Program.cs:line 7

Regression?

SDK 9.0.308: result = [ 2, 3 ]
SDK 10.0.102: System.ArgumentOutOfRangeException

Known Workarounds

If insert Select(x => x) method before the Concat(), it solves the problem.

Configuration

.NET SDK:
Version: 10.0.102
Commit: 4452502459
Workload version: 10.0.100-manifests.6d969a7e
MSBuild version: 18.0.7+445250245

Runtime Environment:
OS Name: Windows
OS Version: 10.0.26200
OS Platform: Windows
RID: win-x64
Base Path: C:\Program Files\dotnet\sdk\10.0.102\

Other information

No response

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions