Interesting question.
wrote:
I don't understand why the elements in arr are changed but not in list. Could someone explain it to me?
To understand why the results are different, you need to understand what is happening when
foreach
is compiled. Compiler translates
foreach
depending on it's usage.
- When
foreach
is used to iterate over an array, compiler compiles it into normal for loop. - When the type is not an array, compiler checks for
GetEnumerator
method and use it. The enumerator object returned by GetEnumerator
method will be used for the processing..
Considering the above facts, your code for changing elements in an array compiles as a normal
for loop and changing elements in list compiles as(written on this editor directly).
List<String^>^::Enumerator^ enumerator = list->GetEnumerator();
while(true)
{
if(!enumerator->MoveNext())
{
break;
}
String^ str = enumerator.Current; str = }
So whatever object you are changing is a copy of real object available in the list. Hence the changes won't be seen.
However, I am surprised to see the code compiles on C++/CLI. In C#, changing a
foreach
variable will yield into an error.
Hope that helps.