Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections;
using System.Collections.Generic;

Expand Down Expand Up @@ -77,9 +78,10 @@ public override int GetCount(bool onlyIfCheap)
if (index == 0)
{
found = true;
return _default;
}

return _default;
return default;
}
}
}
Expand Down
31 changes: 31 additions & 0 deletions src/libraries/System.Linq/tests/DefaultIfEmptyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,36 @@ public void First_Last_ElementAt()
Assert.Equal(42, empty.DefaultIfEmpty(42).ElementAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => empty.DefaultIfEmpty(42).ElementAt(1));
}

[Fact]
public void ElementAtOrDefault_OutOfBounds_ReturnsTypeDefault()
{
// Regression test for https://github.com/dotnet/runtime/issues/119834
// ElementAtOrDefault should return default(T) for out-of-bounds indices,
// not the DefaultIfEmpty default value

// Test with empty source
int[] empty = [];
var defaultIfEmpty = empty.DefaultIfEmpty(999);

// Index 0 should return the DefaultIfEmpty value (999)
Assert.Equal(999, defaultIfEmpty.ElementAtOrDefault(0));

// Out-of-bounds indices should return default(int) which is 0, not 999
Assert.Equal(0, defaultIfEmpty.ElementAtOrDefault(1));
Assert.Equal(0, defaultIfEmpty.ElementAtOrDefault(2));
Assert.Equal(0, defaultIfEmpty.ElementAtOrDefault(-1));

// Test with different type (string)
string[] emptyStrings = [];
var defaultIfEmptyString = emptyStrings.DefaultIfEmpty("default");

// Index 0 should return the DefaultIfEmpty value
Assert.Equal("default", defaultIfEmptyString.ElementAtOrDefault(0));

// Out-of-bounds indices should return default(string) which is null
Assert.Null(defaultIfEmptyString.ElementAtOrDefault(1));
Assert.Null(defaultIfEmptyString.ElementAtOrDefault(2));
}
}
}
Loading