for each, in
Use the for each statement to iterate through an array or collection.
Syntax
for each (type identifier in expression) {
statements
}
Parameters
Remarks
The for each statement is used to iterate through a collection. It is possible to modify elements in a collection, but you cannot add or delete elements.
The statements are executed for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the for each block.
for each and in are context-sensitive keywords; see Context-Sensitive Keywords (C++ Component Extensions) for more information.
In the development environment, you can get F1 help on by highlighting the keyword, (for each) and pressing F1.
For more information, see,
(There are no Windows Runtime-specific remarks for this language feature.)
Example
This sample shows how to iterate through a string with for each.
// for_each_string1.cpp
// compile with: /ZW
#include <stdio.h>
using namespace Platform;
ref struct MyClass {
property String^ MyStringProperty;
};
int main() {
String^ MyString = ref new String("abcd");
for each ( char c in MyString )
wprintf("%c", c);
wprintf("/n");
MyClass^ x = ref new MyClass();
x->MyStringProperty = "Testing";
for each( char c in x->MyStringProperty )
wprintf("%c", c);
}
Output
abcd Testing
The following table lists differences from the syntax shown in the All Runtimes section that are specific to C++/CLI.
Parameters
Example
This sample shows how to iterate through a string with for each.
// for_each_string2.cpp
// compile with: /clr
using namespace System;
ref struct MyClass {
property String ^ MyStringProperty;
};
int main() {
String ^ MyString = gcnew String("abcd");
for each ( Char c in MyString )
Console::Write(c);
Console::WriteLine();
MyClass ^ x = gcnew MyClass();
x->MyStringProperty = "Testing";
for each( Char c in x->MyStringProperty )
Console::Write(c);
}
Output
abcd Testing