@@ -940,7 +940,10 @@ private BoundStatement LowerCollectionRange(BoundForRangeStatement node, bool is
940940 // continues to destructure into `Current.Key` / `Current.Value`.
941941 if ( node . KeyVariable == null )
942942 {
943- statements . Add ( new BoundVariableDeclaration ( node . Syntax , node . ValueVariable , currentAccess ) ) ;
943+ statements . Add ( new BoundVariableDeclaration (
944+ node . Syntax ,
945+ node . ValueVariable ,
946+ ConvertEnumeratorCurrent ( currentAccess , node . ValueVariable . Type ) ) ) ;
944947 }
945948 else
946949 {
@@ -986,7 +989,10 @@ private BoundStatement LowerCollectionRange(BoundForRangeStatement node, bool is
986989 statements . Add ( new BoundVariableDeclaration ( node . Syntax , node . KeyVariable , new BoundVariableExpression ( node . Syntax , indexSymbol ) ) ) ;
987990 }
988991
989- statements . Add ( new BoundVariableDeclaration ( node . Syntax , node . ValueVariable , currentAccess ) ) ;
992+ statements . Add ( new BoundVariableDeclaration (
993+ node . Syntax ,
994+ node . ValueVariable ,
995+ ConvertEnumeratorCurrent ( currentAccess , node . ValueVariable . Type ) ) ) ;
990996 }
991997
992998 statements . Add ( node . Body ) ;
@@ -1055,6 +1061,13 @@ private BoundStatement LowerCollectionRange(BoundForRangeStatement node, bool is
10551061 return new BoundBlockStatement ( node . Syntax , statements . ToImmutable ( ) ) ;
10561062 }
10571063
1064+ private static BoundExpression ConvertEnumeratorCurrent ( BoundExpression current , TypeSymbol elementType )
1065+ {
1066+ return current . Type == TypeSymbol . Object || current . Type ? . ClrType . IsSameAs ( typeof ( object ) ) == true
1067+ ? new BoundConversionExpression ( current . Syntax , elementType , current )
1068+ : current ;
1069+ }
1070+
10581071 private static BoundExpression TryBuildEnumeratorDisposeCall ( LocalVariableSymbol enumeratorSymbol )
10591072 {
10601073 var clrType = enumeratorSymbol . Type ? . ClrType ;
0 commit comments