With loops, code is executed repeatedly until a condition is met. Loops with C# are discussed in Chapter 2, “C# Basics,” including: for, while, do..while, and foreach. C# and C++/CLI are very similar with these statements, Visual Basic defines different statements.
The for statement is similar with C# and C++/CLI. With Visual Basic, you can’t initialize a variable inside the For/To statement, you must initialize the variable beforehand. For/To doesn’t require a Step to follow - Step 1 is the default. Just in case you don’t want to increment by 1, the Step keyword is required with For/To.
// C# for (int i = 0; i < 100; i++) { Console.WriteLine(i); } // C++/CLI for (int i = 0; i < 100; i++) { Console::WriteLine(i); } ' Visual Basic Dim count as Integer For count = 0 To 99 Step 1 Console.WriteLine(count) Next
The while and do..while statements are the same in C# and C++/CLI. Visual Basic has very similar constructs with Do While/Loop and Do/Loop While.
// C# int i = 0; while (i < 3) { Console.WriteLine(i++); } i = 0; do { Console.WriteLine(i++); } while (i < 3); // C++/CLI int i = 0; while (i < 3) { Console::WriteLine(i++); } i = 0; do { Console::WriteLine(i++); } while (i < 3); ' Visual Basic Dim num as Integer = 0 Do While (num < 3) Console.WriteLine(num) num += 1 Loop num = 0 Do Console.WriteLine(num) num += 1 Loop While (num < 3)
The foreach statement makes use of the interface IEnumerable. foreach doesn’t exist with ANSI C++ but is an extension with ANSI C++/CLI. Unlike the C# foreach, in C++/CLI there’s a blank space between for and each. The For Each statement of Visual Basic doesn’t allow you to declare the type of the iterating type inside the loop; the type must be declared beforehand.
// C# int[] arr = {1, 2, 3}; foreach (int i in arr) { Console.WriteLine(i); } // C++/CLI array<int>^ arr = {1, 2, 3}; for each (int i in arr) { Console::WriteLine(i); } ' Visual Basic Dim arr() As Integer = New Integer() {1, 2, 3} Dim num As Integer For Each num In arr Console.WriteLine(num) Next