Cute
Cute

Reputation: 14021

How to use foreach in c++ cli in managed code

Hi how to use foreach loop in managed code c++ using vs2003.

Upvotes: 26

Views: 41232

Answers (5)

Matthew Flaschen
Matthew Flaschen

Reputation: 284977

I've never used it, but this MSDN article indicates the general syntax is just:

for each(Type t in IEnumerable)
{

}

Upvotes: 48

Scott Madeux
Scott Madeux

Reputation: 429

As of VS2022 for each apparently no longer works. Instead you can do something like this:

IEnumerator^ enumerator = myList->GetEnumerator();
while (enumerator->MoveNext())
{
    // Do stuff
}

Upvotes: 2

Aamir
Aamir

Reputation: 15576

Something like:

String ^ MyString = gcnew String("abcd");

for each ( Char c in MyString )

    Console::Write(c);

Upvotes: 2

RandomNickName42
RandomNickName42

Reputation: 5965

Matthew is mostly correct, but here's a working block of code;

///////
array<Type^>^ iterate_me = gcnew array<Type^>(2);
iterate_me[0] = Type::GetType("Type");
iterate_me[1] = Type::GetType("System.Int32");
///////

for each(Type^ t in iterate_me)
    Console::WriteLine(t);

The changes were Type is a reference class, so you use "Type^" not "Type" and you need an actual object reference (iterate_me)...

Upvotes: 17

hkhalifa
hkhalifa

Reputation: 1255

I don't think that VC++ has foreach

Upvotes: -9

Related Questions