Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Repeating Block Statements
  Do...Loop Statement
  Syntax
  Parts
  Remarks
  Exit Do
  See also
  For Each...Next Statement
  Syntax
  Parts
  Nested Loops
  Exit For and Continue For
  Iterators
  Technical Implementation
  Narrowing Conversions
  IEnumerator Calls
  See also
  For...Next Statement
  Syntax
  Parts
  Nesting Loops
  Exit For and Continue For
  Technical Implementation
  Step Argument
  Counter Argument
  See also
  Source/Reference

VB.NET Repeating Block Statements

The supporting VB.NET Repeating Block Statements are Do…Loop, For Each…Next, For…Next,             While...End While

Do...Loop Statement

Repeats a block of statements while a Boolean condition is True or until the condition becomes True.

Syntax

Do { 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

Term Definition
Do Required. Starts the definition of the Do loop.
While Required unless Until is used. Repeat the loop until condition is False.
Until Required unless While is used. Repeat the loop until condition is True.
condition Optional. Boolean expression. If condition is Nothing, Visual Basic treats it as False.
statements Optional. One or more statements that are repeated while, or until, condition is True.
Continue Do Optional. Transfers control to the next iteration of the Do loop.
Exit Do Optional. Transfers control out of the Do loop.
Loop Required. Terminates the definition of the Do loop.

Remarks

Use 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 Do

The 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 Statement

Repeats a group of statements for each element in a collection.

Syntax

For Each element [ As datatype ] In group  
    [ statements ]  
    [ Continue For ]  
    [ statements ]  
    [ Exit For ]  
    [ statements ]  
Next [ element ]  

Parts

Term Definition
element Required in the For Each statement. Optional in the Next statement. Variable. Used to iterate through the elements of the collection.
datatype Optional if Option Infer is on (the default) or element is already declared; required if Option Infer is off and element isn't already declared. The data type of element.
group Required. A variable with a type that's a collection type or Object. Refers to the collection over which the statements are to be repeated.
statements Optional. One or more statements between For Each and Next that run on each item in group.
Continue For Optional. Transfers control to the start of the For Each loop.
Exit For Optional. Transfers control out of the For Each loop.
Next Required. Terminates the definition of the For Each loop.

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 Loops

You 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 For

The 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:

  • Continuing to iterate is unnecessary or impossible. This might be caused by an erroneous value or a termination request.

  • An exception is caught in a Try...Catch...Finally. You might use Exit For at the end of the Finally block.

  • There an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement.

Iterators

You 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 Implementation

When 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 Conversions

When 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 Calls

When 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 Statement

Repeats a group of statements a specified number of times.

Syntax

For counter [ As datatype ] = start To end [ Step step ]  
    [ statements ]  
    [ Continue For ]  
    [ statements ]  
    [ Exit For ]  
    [ statements ]  
Next [ counter ]  

Parts

Part Description
counter Required in the For statement. Numeric variable. The control variable for the loop. For more information, see Counter Argument later in this topic.
datatype Optional. Data type of counter. For more information, see Counter Argument later in this topic.
start Required. Numeric expression. The initial value of counter.
end Required. Numeric expression. The final value of counter.
step Optional. Numeric expression. The amount by which counter is incremented each time through the loop.
statements Optional. One or more statements between For and Next that run the specified number of times.
Continue For Optional. Transfers control to the next loop iteration.
Exit For Optional. Transfers control out of the For loop.
Next Required. Terminates the definition of the For loop.

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 Loops

You 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 For

The 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:

  • Continuing to iterate is unnecessary or impossible. An erroneous value or a termination request might create this condition.

  • A Try...Catch...Finally statement catches an exception. You might use Exit For at the end of the Finally block.

  • You have an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement.

Technical Implementation

When 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 Argument

The value of step can be either positive or negative. This parameter determines loop processing according to the following table:

Step value Loop executes if
Positive or zero counter <= end
Negative counter >= end

The default value of step is 1.

Counter Argument

The 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.

Is datatype present? Is counter already defined? Result (whether counter defines a new local variable that’s scoped to the entire For...Next loop)
No Yes No, because counter is already defined. If the scope of counter isn't local to the procedure, a compile-time warning occurs.
No No Yes. The data type is inferred from the start, end, and step expressions. For information about type inference, see Option Infer Statement and Local Type Inference.
Yes Yes Yes, but only if the existing counter variable is defined outside the procedure. That variable remains separate. If the scope of the existing counter variable is local to the procedure, a compile-time error occurs.
Yes No Yes.

The data type of counter determines the type of the iteration, which must be one of the following types:

  • A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

  • An enumeration that you declare by using an Enum Statement.

  • An Object.

  • A type T that has the following operators, where B is a type that can be used in a Boolean expression.

    Public Shared Operator >= (op1 As T, op2 As T) As B

    Public Shared Operator <= (op1 As T, op2 As T) As B

    Public Shared Operator - (op1 As T, op2 As T) As T

    Public Shared Operator + (op1 As T, op2 As T) As T

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:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019