Consider the following C# code.
string[] stringArray = new string[10];
foreach (string s in stringArray)
s = "a new string"; // Compiler error - Can't assign to foreach iteration variable
Now consider the following valid C++/CLI code.
array<String^>^ stringArray = gcnew array<String^>(10);
for each(String^% s in stringArray)
s = "a new string";
When foreach
is used with array type, compiler translates it into normal for
loop. This implementation is same for C# and C++/CLI. So I wonder if C++/CLI can allow this, why not for C# compiler?
This error makes sense when the type is not an array as foreach
will be compiled into GetEnumerator
call and use the enumerator for iteration. But I think it can be allowed for array types.
Any thoughts?
As a side note, the following is a valid C++/CLI code too but will not produce the expected result.
List<String^>^ stringList = gcnew List<String^>(10);
for each(String^% s in stringList)
s = "a new string"; // I think this should be prevented by compiler as it makes no sense.