InternetUnicodeHTMLCSSScalable Vector Graphics (SVG)Extensible Markup Language (xml) ASP.Net TOCASP.NetMiscellaneous Feature ASP.NET Scripting Visual Basic .NET TOCVB .NET Language ReferencenaVB.Net ElementsVB.NET Operators StatementComment StatementsAssignment StatementsDeclaration Statements Draft for Information Only
Content
VB.NET Repeating Block Statements
VB.NET Repeating Block StatementsThe supporting VB.NET Repeating Block Statements are Do…Loop, For Each…Next, For…Next, While...End While Do...Loop StatementRepeats a block of statements while a Boolean condition is True or until the condition becomes True. SyntaxDo { While | Until } condition [ statements ] [ Continue Do ] [ statements ] [ Exit Do ] [ statements ] Loop -or- Do [ statements ] [ Continue Do ] [ statements ] [ Exit Do ] [ statements ] Loop { While | Until } condition Parts
RemarksUse a Do...Loop structure when you want to repeat a set of statements an indefinite number of times, until a condition is satisfied. If you want to repeat the statements a set number of times, the For...Next Statement is usually a better choice. You can use either While or Until to specify condition, but not both. You can test condition only one time, at either the start or the end of the loop. If you test condition at the start of the loop (in the Do statement), the loop might not run even one time. If you test at the end of the loop (in the Loop statement), the loop always runs at least one time. The condition usually results from a comparison of two values, but it can be any expression that evaluates to a Boolean Data Type value (True or False). This includes values of other data types, such as numeric types, that have been converted to Boolean. You can nest Do loops by putting one loop within another. You can also nest different kinds of control structures within each other. For more information, see Nested Control Structures. Note The Do...Loop structure gives you more flexibility than the While...End While Statement because it enables you to decide whether to end the loop when condition stops being True or when it first becomes True. It also enables you to test condition at either the start or the end of the loop. Exit DoThe Exit Do statement can provide an alternative way to exit a Do…Loop. Exit Do transfers control immediately to the statement that follows the Loop statement. Exit Do is often used after some condition is evaluated, for example in an If...Then...Else structure. You might want to exit a loop if you detect a condition that makes it unnecessary or impossible to continue iterating, such as an erroneous value or a termination request. One use of Exit Do is to test for a condition that could cause an endless loop, which is a loop that could run a large or even infinite number of times. You can use Exit Do to escape the loop. You can include any number of Exit Do statements anywhere in a Do…Loop. When used within nested Do loops, Exit Do transfers control out of the innermost loop and into the next higher level of nesting. See also
For Each...Next StatementRepeats a group of statements for each element in a collection. SyntaxFor Each element [ As datatype ] In group [ statements ] [ Continue For ] [ statements ] [ Exit For ] [ statements ] Next [ element ] Parts
Use a For Each...Next loop when you want to repeat a set of statements for each element of a collection or array. Tip A For...Next Statement works well when you can associate each iteration of a loop with a control variable and determine that variable's initial and final values. However, when you are dealing with a collection, the concept of initial and final values isn't meaningful, and you don't necessarily know how many elements the collection has. In this kind of case, a For Each...Next loop is often a better choice. Nested LoopsYou can nest For Each loops by putting one loop within another. When you nest loops, each loop must have a unique element variable. You can also nest different kinds of control structures within each other. For more information, see Nested Control Structures. Exit For and Continue ForThe Exit For statement causes execution to exit the For…Next loop and transfers control to the statement that follows the Next statement. The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement. You can put any number of Exit For statements in a For Each loop. When used within nested For Each loops, Exit For causes execution to exit the innermost loop and transfers control to the next higher level of nesting. Exit For is often used after an evaluation of some condition, for example, in an If...Then...Else structure. You might want to use Exit For for the following conditions:
IteratorsYou use an iterator to perform a custom iteration over a collection. An iterator can be a function or a Get accessor. It uses a Yield statement to return each element of the collection one at a time. You call an iterator by using a For Each...Next statement. Each iteration of the For Each loop calls the iterator. When a Yield statement is reached in the iterator, the expression in the Yield statement is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator is called. For more information, see Iterators, Yield Statement, and Iterator. Technical ImplementationWhen a For Each…Next statement runs, Visual Basic evaluates the collection only one time, before the loop starts. If your statement block changes element or group, these changes don't affect the iteration of the loop. When all the elements in the collection have been successively assigned to element, the For Each loop stops and control passes to the statement following the Next statement. If Option Infer is on (its default setting), the Visual Basic compiler can infer the data type of element. If it is off and element hasn't been declared outside the loop, you must declare it in the For Each statement. To declare the data type of element explicitly, use an As clause. Unless the data type of element is defined outside the For Each...Next construct, its scope is the body of the loop. Note that you cannot declare element both outside and inside the loop. You can optionally specify element in the Next statement. This improves the readability of your program, especially if you have nested For Each loops. You must specify the same variable as the one that appears in the corresponding For Each statement. You might want to avoid changing the value of element inside a loop. Doing this can make it more difficult to read and debug your code. Changing the value of group doesn't affect the collection or its elements, which were determined when the loop was first entered. When you're nesting loops, if a Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an error. However, the compiler can detect this overlapping error only if you specify element in every Next statement. If your code depends on traversing a collection in a particular order, a For Each...Next loop isn't the best choice, unless you know the characteristics of the enumerator object the collection exposes. The order of traversal isn't determined by Visual Basic, but by the MoveNext method of the enumerator object. Therefore, you might not be able to predict which element of the collection is the first to be returned in element, or which is the next to be returned after a given element. You might achieve more reliable results using a different loop structure, such as For...Next or Do...Loop. The runtime must be able to convert the elements in group to element. The [Option Strict] statement controls whether both widening and narrowing conversions are allowed (Option Strict is off, its default value), or whether only widening conversions are allowed (Option Strict is on). For more information, see Narrowing conversions. The data type of group must be a reference type that refers to a collection or an array that's enumerable. Most commonly this means that group refers to an object that implements the IEnumerable interface of the System.Collections namespace or the IEnumerable<T> interface of the System.Collections.Generic namespace. System.Collections.IEnumerable defines the GetEnumerator method, which returns an enumerator object for the collection. The enumerator object implements the System.Collections.IEnumerator interface of the System.Collections namespace and exposes the Current property and the Reset and MoveNext methods. Visual Basic uses these to traverse the collection. Narrowing ConversionsWhen Option Strict is set to On, narrowing conversions ordinarily cause compiler errors. In a For Each statement, however, conversions from the elements in group to element are evaluated and performed at run time, and compiler errors caused by narrowing conversions are suppressed. IEnumerator CallsWhen execution of a For Each...Next loop starts, Visual Basic verifies that group refers to a valid collection object. If not, it throws an exception. Otherwise, it calls the MoveNext method and the Current property of the enumerator object to return the first element. If MoveNext indicates that there is no next element, that is, if the collection is empty, the For Each loop stops and control passes to the statement following the Next statement. Otherwise, Visual Basic sets element to the first element and runs the statement block. Each time Visual Basic encounters the Next statement, it returns to the For Each statement. Again it calls MoveNext and Current to return the next element, and again it either runs the block or stops the loop depending on the result. This process continues until MoveNext indicates that there is no next element or an Exit For statement is encountered. Modifying the Collection. The enumerator object returned by GetEnumerator normally doesn't let you change the collection by adding, deleting, replacing, or reordering any elements. If you change the collection after you have initiated a For Each...Next loop, the enumerator object becomes invalid, and the next attempt to access an element causes an InvalidOperationException exception. However, this blocking of modification isn't determined by Visual Basic, but rather by the implementation of the IEnumerable interface. It is possible to implement IEnumerable in a way that allows for modification during iteration. If you are considering doing such dynamic modification, make sure that you understand the characteristics of the IEnumerable implementation on the collection you are using. Modifying Collection Elements. The Current property of the enumerator object is ReadOnly, and it returns a local copy of each collection element. This means that you cannot modify the elements themselves in a For Each...Next loop. Any modification you make affects only the local copy from Current and isn't reflected back into the underlying collection. However, if an element is a reference type, you can modify the members of the instance to which it points. Traversing Arrays. Because the Array class implements the IEnumerable interface, all arrays expose the GetEnumerator method. This means that you can iterate through an array with a For Each...Next loop. However, you can only read the array elements. You cannot change them. See also
For...Next StatementRepeats a group of statements a specified number of times. SyntaxFor counter [ As datatype ] = start To end [ Step step ] [ statements ] [ Continue For ] [ statements ] [ Exit For ] [ statements ] Next [ counter ] Parts
Note The To keyword is used in this statement to specify the range for the counter. You can also use this keyword in the Select...Case Statement and in array declarations. For more information about array declarations, see Dim Statement. You use a For...Next structure when you want to repeat a set of statements a set number of times. Tip A While...End While Statement or Do...Loop Statement works well when you don't know in advance how many times to run the statements in the loop. However, when you expect to run the loop a specific number of times, a For...Next loop is a better choice. You determine the number of iterations when you first enter the loop. Nesting LoopsYou can nest For loops by putting one loop within another. When nesting loops, each loop must have a unique counter variable. You can also nest different kinds control structures within each other. For more information, see Nested Control Structures. Exit For and Continue ForThe Exit For statement immediately exits the For…Next loop and transfers control to the statement that follows the Next statement. The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement. You can put any number of Exit For statements in a For…Next loop. When used within nested For…Next loops, Exit For exits the innermost loop and transfers control to the next higher level of nesting. Exit For is often used after you evaluate some condition (for example, in an If...Then...Else structure). You might want to use Exit For for the following conditions:
Technical ImplementationWhen a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic evaluates these values only at this time and then assigns start to counter. Before the statement block runs, Visual Basic compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement. Otherwise, the statement block runs. Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the For statement. Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. This process continues until counter passes end or an Exit For statement is encountered. The loop doesn't stop until counter has passed end. If counter is equal to end, the loop continues. The comparison that determines whether to run the block is counter <= end if step is positive and counter >= end if step is negative. If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered. If you nest loops, the compiler signals an error if it encounters the Next statement of an outer nesting level before the Next statement of an inner level. However, the compiler can detect this overlapping error only if you specify counter in every Next statement. Step ArgumentThe value of step can be either positive or negative. This parameter determines loop processing according to the following table:
The default value of step is 1. Counter ArgumentThe following table indicates whether counter defines a new local variable that’s scoped to the entire For…Next loop. This determination depends on whether datatype is present and whether counter is already defined.
The data type of counter determines the type of the iteration, which must be one of the following types:
You can optionally specify the counter variable in the Next statement. This syntax improves the readability of your program, especially if you have nested For loops. You must specify the variable that appears in the corresponding For statement. The start, end, and step expressions can evaluate to any data type that widens to the type of counter. If you use a user-defined type for counter, you might have to define the CType conversion operator to convert the types of start, end, or step to the type of counter. See also
Source/Reference
©sideway ID: 200800015 Last Updated: 8/15/2020 Revision: 0 Ref: ![]() References
![]() Latest Updated Links
![]() ![]() ![]() ![]() ![]() |
![]() Home 5 Business Management HBR 3 Information Recreation Hobbies 8 Culture Chinese 1097 English 339 Travel 18 Reference 79 Computer Hardware 254 Software Application 213 Digitization 37 Latex 52 Manim 205 KB 1 Numeric 19 Programming Web 289 Unicode 504 HTML 66 CSS 65 SVG 46 ASP.NET 270 OS 431 DeskTop 7 Python 72 Knowledge Mathematics Formulas 8 Set 1 Logic 1 Algebra 84 Number Theory 206 Trigonometry 31 Geometry 34 Calculus 67 Engineering Tables 8 Mechanical Rigid Bodies Statics 92 Dynamics 37 Fluid 5 Control Acoustics 19 Natural Sciences Matter 1 Electric 27 Biology 1 |
Copyright © 2000-2025 Sideway . All rights reserved Disclaimers last modified on 06 September 2019