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.
Reproduction Steps
HashSet<int>.Enumerator enumerator = default;
if (enumerator.MoveNext()) {
// do something
}
Expected behavior
Nothing has happened.
Actual behavior
Throw NullReferenceException
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
Description
Many value-type enumerators in the standard library collections do not take into account the scenario where they are constructed via
defaultornew(). As a result, calling theirMoveNext()method unexpectedly throws aNullReferenceException. The API documentation also does not mention thatMoveNext()may throwNullReferenceException, 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.
Reproduction Steps
Expected behavior
Nothing has happened.
Actual behavior
Throw
NullReferenceExceptionRegression?
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