Skip to content

Value enumerators do not account for being constructed via default, unexpectedly throwing NullReferenceException. #131702

Description

@GameMicrowave

Description

Many value-type enumerators in the standard library collections do not take into account the scenario where they are constructed via default or new(). As a result, calling their MoveNext() method unexpectedly throws a NullReferenceException. The API documentation also does not mention that MoveNext() may throw NullReferenceException, which is clearly an oversight in the design.

These value enumerators internally store some reference-type fields, but their methods access members of those fields without checking for null. Since default and similar means can directly construct such enumerators with all reference fields set to null, this issue arises.

Image Image

Reproduction Steps

HashSet<int>.Enumerator enumerator = default;
if (enumerator.MoveNext()) {
  // do something
}

Expected behavior

Nothing has happened.

Actual behavior

Throw NullReferenceException

Image

Regression?

No response

Known Workarounds

Add a null check at the very beginning of the method to determine whether it is in the default state. If so, exit immediately.

Configuration

No response

Other information

No response

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