Skip to content

The new SZGenericArrayEnumerator unexpectedly throws errors for empty collections #94256

@icom85

Description

@icom85

Description

Hello! We encountered an issue related to the base SZGenericArrayEnumerator type and its Current position. This seems to be a breaking change as the issue got introduced in .NET 8 preview 2 - https://versionsof.net/core/8.0/8.0.0-preview.2/.

Reproduction Steps

Create an empty list like this:

 List<int> items = new List<int>();

Imagine that you have a more generic method accepting IEnumerable as a parameter and you call that method and pass the empty list. Inside the method you want to move and access the current item:

private void GetNext(IEnumerable<int> items)
{
    IEnumerator<int> enumerator = items.GetEnumerator();
    enumerator.MoveNext();
    int current = enumerator.Current;
}

If you check for the Current directly, you will get: System.InvalidOperationException: 'Enumeration has not started. Call MoveNext.'
If you call MoveNext() and then check the Current, you will get: System.InvalidOperationException: 'Enumeration already finished.'

The type of the enumerator is: SZGenericArrayEnumerator.
image

Prior to NET 8 preview 2, in the same setup you would get a System.Collections.Generic.List.Enumerator and you would not get errors, the Current would be 0.

It seems that the new and concrete implementation for the enumerator that is returned for the base types is causing the error. This may cause runtime issues with existing application if they are run in .net8.0.

Expected behavior

The Current should not throw.

Actual behavior

Errors are thrown.

Regression?

Yes, the behavior was different in .NET 8 preview 1 and before.

Known Workarounds

Use MoveNext and only access the Current item if the enumerator has successfully moved to the next position.

private void GetNext(IEnumerable<int> items)
{
    IEnumerator<int> enumerator = items.GetEnumerator();
    if (enumerator.MoveNext())
    {
        int current = enumerator.Current;
    }
}

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions