You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#nullable enable
using System.Collections;using System.Collections.Generic;publicclassC{publicvoidM(){varc=new BarCollection();foreach(Bar b in c){}// warning CS8606: Possible null reference assignment to iteration variableforeach(Zoo? z in c){}// ok}}publicclassBarCollection:IEnumerable,IEnumerable<Bar>{public IEnumerator GetEnumerator()=>null!;IEnumerator<Bar>IEnumerable<Bar>.GetEnumerator()=>null!;}publicclassBar{}publicclassZoo{}
The foreach (Bar b in c) will incur a nullable warning, because IEnumerator.Current is typed to return object?. However, foreach over a non-generic IEnumerable allows the iteration variable to be of any type, without warning, as highlighted by the foreach (Zoo? z in c) which has no warnings, even though it'll blow up at run time due to a failed cast.
We should change the nullable heuristics to simply not warn for the iteration variable when foreach binds to the non-generic IEnumerable.
Updated proposal: could we special-case for nullability the case where the type being enumerated implements IEnumerable<T>, and if the dev specifies T as the iteration variable or anything in its inheritance hierarchy, and if T is defined as non-nullable, treating it as non-null?
Consider:
The
foreach (Bar b in c)
will incur a nullable warning, becauseIEnumerator.Current
is typed to returnobject?
. However,foreach
over a non-genericIEnumerable
allows the iteration variable to be of any type, without warning, as highlighted by theforeach (Zoo? z in c)
which has no warnings, even though it'll blow up at run time due to a failed cast.We should change the nullable heuristics to simply not warn for the iteration variable when foreach binds to the non-generic
IEnumerable
.Updated proposal: could we special-case for nullability the case where the type being enumerated implements
IEnumerable<T>
, and if the dev specifiesT
as the iteration variable or anything in its inheritance hierarchy, and ifT
is defined as non-nullable, treating it as non-null?cc: @agocke, @jcouv
The text was updated successfully, but these errors were encountered: