For Each Loop in Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes how to use the For Each loop in Visual Basic .NET.
The For Each loop iterates over the items in a collection, array, or other container class that supports For Each loops.
Its syntax is as follows:
For Each variable [As object_type ] In group statements [Exit For] statements [Continue For] statements Next [ variable ]In this loop, group is a collection, array, or other object that supports For Each and it's important that control variable must be of a data type compatible with the objects contained in the group.
Visual Basic doesn't automatically understand what kind of objects are stored in a collection or array until it "tries" to use them.
If the control variable's type is not compatible with an object's type, the program generates an error.
For Each user As User In Users Console.WriteLine(user.Username) Next user
Note: Visual Basic doesn't require the variable's name in the Next statement, but it makes the code easier to read Previous Lesson | Next Lesson