For Loops

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

For...

Next Statement (Visual


Basic)
 Article
 09/15/2021
 13 contributors
Feedback

In this article
1. Syntax
2. Parts
3. Simple Examples
4. Nesting Loops
Show 6 more

Repeats a group of statements a specified number of times.

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

Parts
Expand table
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
Part Description
times.
Continue Optional. Transfers control to the next loop iteration.
For
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.

Simple Examples
You use a For...Next structure when you want to repeat a set of statements a
set number of times.

In the following example, the index variable starts with a value of 1 and is
incremented with each iteration of the loop, ending after the value
of index reaches 5.

VBCopy
For index As Integer = 1 To 5
Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5

In the following example, the number variable starts at 2 and is reduced by


0.25 on each iteration of the loop, ending after the value of number reaches 0.
The Step argument of -.25 reduces the value by 0.25 on each iteration of the
loop.

VBCopy
For number As Double = 2 To 0 Step -0.25
Debug.Write(number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0
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. The following
example demonstrates nested For...Next structures that have different step
values. The outer loop creates a string for every iteration of the loop. The
inner loop decrements a loop counter variable for every iteration of the loop.

VBCopy
For indexA = 1 To 3
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()

' Append to the StringBuilder every third number


' from 20 to 1 descending.
For indexB = 20 To 1 Step -3
sb.Append(indexB.ToString)
sb.Append(" ")
Next indexB

' Display the line.


Debug.WriteLine(sb.ToString)
Next indexA
' Output:
' 20 17 14 11 8 5 2
' 20 17 14 11 8 5 2
' 20 17 14 11 8 5 2

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.

The following example illustrates the use of the Continue For and Exit
For statements.
VBCopy
For index As Integer = 1 To 100000
' If index is between 5 and 7, continue
' with the next iteration.
If index >= 5 AndAlso index <= 8 Then
Continue For
End If

' Display the index.


Debug.Write(index.ToString & " ")

' If index is 10, exit the loop.


If index = 10 Then
Exit For
End If
Next
Debug.WriteLine("")
' Output: 1 2 3 4 9 10

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.

Object-oriented programming
(Visual Basic)
 Article
 09/15/2021
 8 contributors
Feedback

In this article
1. Classes and objects
2. Inheritance
3. Interfaces
4. Generics
Show 2 more

Visual Basic provides full support for object-oriented programming including


encapsulation, inheritance, and polymorphism.

Encapsulation means that a group of related properties, methods, and other


members are treated as a single unit or object.
Inheritance describes the ability to create new classes based on an existing
class.

Polymorphism means that you can have multiple classes that can be used
interchangeably, even though each class implements the same properties or
methods in different ways.

This section describes the following concepts:

 Classes and objects


o Class members
o Properties and fields
o Methods
o Constructors
o Destructors
o Events
o Nested classes
o Access modifiers and access levels
o Instantiating classes
o Shared classes and members
o Anonymous types
 Inheritance
o Overriding members
 Interfaces
 Generics
 Delegates

Classes and objects


The terms class and object are sometimes used interchangeably, but in fact,
classes describe the type of objects, while objects are usable instances of
classes. So, the act of creating an object is called instantiation. Using the
blueprint analogy, a class is a blueprint, and an object is a building made
from that blueprint.

To define a class:

VBCopy
Class SampleClass
End Class

Visual Basic also provides a light version of classes called structures that are
useful when you need to create large array of objects and do not want to
consume too much memory for that.
To define a structure:

VBCopy
Structure SampleStructure
End Structure

For more information, see:

 Class Statement
 Structure Statement

Class members

Each class can have different class members that include properties that
describe class data, methods that define class behavior, and events that
provide communication between different classes and objects.

Properties and fields

Fields and properties represent information that an object contains. Fields


are like variables because they can be read or set directly.

To define a field:

VBCopy
Class SampleClass
Public SampleField As String
End Class

Properties have get and set procedures, which provide more control on how
values are set or returned.

Visual Basic allows you either to create a private field for storing the property
value or use so-called auto-implemented properties that create this field
automatically behind the scenes and provide the basic logic for the property
procedures.

To define an auto-implemented property:

VBCopy
Class SampleClass
Public Property SampleProperty as String
End Class
If you need to perform some additional operations for reading and writing the
property value, define a field for storing the property value and provide the
basic logic for storing and retrieving it:

VBCopy
Class SampleClass
Private m_Sample As String
Public Property Sample() As String
Get
' Return the value stored in the field.
Return m_Sample
End Get
Set(ByVal Value As String)
' Store the value in the field.
m_Sample = Value
End Set
End Property
End Class

Most properties have methods or procedures to both set and get the
property value. However, you can create read-only or write-only properties to
restrict them from being modified or read. In Visual Basic you can
use ReadOnly and WriteOnly keywords. However, auto-implemented properties
cannot be read-only or write-only.

For more information, see:

 Property Statement
 Get Statement
 Set Statement
 ReadOnly
 WriteOnly

Methods

A method is an action that an object can perform.

Note

In Visual Basic, there are two ways to create a method: the Sub statement is
used if the method does not return a value; the Function statement is used if
a method returns a value.

To define a method of a class:

VBCopy
Class SampleClass
Public Function SampleFunc(ByVal SampleParam As String)
' Add code here
End Function
End Class

A class can have several implementations, or overloads, of the same method


that differ in the number of parameters or parameter types.

To overload a method:

VBCopy
Overloads Sub Display(ByVal theChar As Char)
' Add code that displays Char data.
End Sub
Overloads Sub Display(ByVal theInteger As Integer)
' Add code that displays Integer data.
End Sub

In most cases you declare a method within a class definition. However, Visual
Basic also supports extension methods that allow you to add methods to an
existing class outside the actual definition of the class.

For more information, see:

 Function Statement
 Sub Statement
 Overloads
 Extension Methods

Constructors

Constructors are class methods that are executed automatically when an


object of a given type is created. Constructors usually initialize the data
members of the new object. A constructor can run only once when a class is
created. Furthermore, the code in the constructor always runs before any
other code in a class. However, you can create multiple constructor
overloads in the same way as for any other method.

To define a constructor for a class:

VBCopy
Class SampleClass
Sub New(ByVal s As String)
// Add code here.
End Sub
End Class
For more information, see: Object Lifetime: How Objects Are Created and
Destroyed.

Destructors

Destructors are used to destruct instances of classes. In the .NET Framework,


the garbage collector automatically manages the allocation and release of
memory for the managed objects in your application. However, you may still
need destructors to clean up any unmanaged resources that your application
creates. There can be only one destructor for a class.

For more information about destructors and garbage collection in the .NET
Framework, see Garbage Collection.

Events

Events enable a class or object to notify other classes or objects when


something of interest occurs. The class that sends (or raises) the event is
called the publisher and the classes that receive (or handle) the event are
called subscribers. For more information about events, how they are raised
and handled, see Events.

 To declare events, use the Event Statement.

 To raise events, use the RaiseEvent Statement.

 To specify event handlers using a declarative way, use


the WithEvents statement and the Handles clause.

 To be able to dynamically add, remove, and change the event


handler associated with an event, use the AddHandler
Statement and RemoveHandler Statement together with
the AddressOf Operator.

Nested classes

A class defined within another class is called nested. By default, the nested
class is private.

VBCopy
Class Container
Class Nested
' Add code here.
End Class
End Class

To create an instance of the nested class, use the name of the container
class followed by the dot and then followed by the name of the nested class:

VBCopy
Dim nestedInstance As Container.Nested = New Container.Nested()

Access modifiers and access levels

All classes and class members can specify what access level they provide to
other classes by using access modifiers.

The following access modifiers are available:

Expand table

Visual Basic Definition


Modifier

Public The type or member can be accessed by any other code in the same assembly or another
assembly that references it.

Private The type or member can only be accessed by code in the same class.

Protected The type or member can only be accessed by code in the same class or in a derived class.

Friend The type or member can be accessed by any code in the same assembly, but not from
another assembly.
Protected The type or member can be accessed by any code in the same assembly, or by any derived
Friend
class in another assembly.

For more information, see Access levels in Visual Basic.

Instantiating classes

To create an object, you need to instantiate a class, or create a class


instance.

VBCopy
Dim sampleObject as New SampleClass()
After instantiating a class, you can assign values to the instance's properties
and fields and invoke class methods.

VBCopy
' Set a property value.
sampleObject.SampleProperty = "Sample String"
' Call a method.
sampleObject.SampleMethod()

To assign values to properties during the class instantiation process, use


object initializers:

VBCopy
Dim sampleObject = New SampleClass With
{.FirstProperty = "A", .SecondProperty = "B"}

For more information, see:

 New Operator
 Object Initializers: Named and Anonymous Types

Shared classes and members

A shared member of the class is a property, procedure, or field that is shared


by all instances of a class.

To define a shared member:

VBCopy
Class SampleClass
Public Shared SampleString As String = "Sample String"
End Class

To access the shared member, use the name of the class without creating an
object of this class:

VBCopy
MsgBox(SampleClass.SampleString)

Shared modules in Visual Basic have shared members only and cannot be
instantiated. Shared members also cannot access non-shared properties,
fields or methods

For more information, see:


 Shared
 Module Statement

Anonymous types

Anonymous types enable you to create objects without writing a class


definition for the data type. Instead, the compiler generates a class for you.
The class has no usable name and contains the properties you specify in
declaring the object.

To create an instance of an anonymous type:

VBCopy
' sampleObject is an instance of a simple anonymous type.
Dim sampleObject =
New With {Key .FirstProperty = "A", .SecondProperty = "B"}

For more information, see: Anonymous Types.

Inheritance
Inheritance enables you to create a new class that reuses, extends, and
modifies the behavior that is defined in another class. The class whose
members are inherited is called the base class, and the class that inherits
those members is called the derived class. However, all classes in Visual
Basic implicitly inherit from the Object class that supports .NET class
hierarchy and provides low-level services to all classes.

Note

Visual Basic doesn't support multiple inheritance. That is, you can specify
only one base class for a derived class.

To inherit from a base class:

VBCopy
Class DerivedClass
Inherits BaseClass
End Class

By default all classes can be inherited. However, you can specify whether a
class must not be used as a base class, or create a class that can be used as
a base class only.
To specify that a class cannot be used as a base class:

VBCopy
NotInheritable Class SampleClass
End Class

To specify that a class can be used as a base class only and cannot be
instantiated:

VBCopy
MustInherit Class BaseClass
End Class

For more information, see:

 Inherits Statement
 NotInheritable
 MustInherit

Overriding members

By default, a derived class inherits all members from its base class. If you
want to change the behavior of the inherited member, you need to override
it. That is, you can define a new implementation of the method, property or
event in the derived class.

The following modifiers are used to control how properties and methods are
overridden:

Expand table

Visual Basic Modifier Definition

Overridable Allows a class member to be overridden in a derived class.

Overrides Overrides a virtual (overridable) member defined in the base class.

NotOverridable Prevents a member from being overridden in an inheriting class.

MustOverride Requires that a class member to be overridden in the derived class.

Shadows Hides a member inherited from a base class

Interfaces
Interfaces, like classes, define a set of properties, methods, and events. But
unlike classes, interfaces do not provide implementation. They are
implemented by classes, and defined as separate entities from classes. An
interface represents a contract, in that a class that implements an interface
must implement every aspect of that interface exactly as it is defined.

To define an interface:

VBCopy
Public Interface ISampleInterface
Sub DoSomething()
End Interface

To implement an interface in a class:

VBCopy
Class SampleClass
Implements ISampleInterface
Sub DoSomething
' Method implementation.
End Sub
End Class

For more information, see:

 Interfaces
 Interface Statement
 Implements Statement

Generics
Classes, structures, interfaces and methods in .NET can include type
parameters that define types of objects that they can store or use. The most
common example of generics is a collection, where you can specify the type
of objects to be stored in a collection.

To define a generic class:

VBCopy
Class SampleGeneric(Of T)
Public Field As T
End Class

To create an instance of a generic class:


VBCopy
Dim sampleObject As New SampleGeneric(Of String)
sampleObject.Field = "Sample string"

For more information, see:

 Generics
 Generic Types in Visual Basic

Delegates
A delegate is a type that defines a method signature, and can provide a
reference to any method with a compatible signature. You can invoke (or
call) the method through the delegate. Delegates are used to pass methods
as arguments to other methods.

Note

Event handlers are nothing more than methods that are invoked through
delegates. For more information about using delegates in event handling,
see Events.

To create a delegate:

VBCopy
Delegate Sub SampleDelegate(ByVal str As String)

To create a reference to a method that matches the signature specified by


the delegate:

VBCopy
Class SampleClass
' Method that matches the SampleDelegate signature.
Sub SampleSub(ByVal str As String)
' Add code here.
End Sub
' Method that instantiates the delegate.
Sub SampleDelegateSub()
Dim sd As SampleDelegate = AddressOf SampleSub
sd("Sample string")
End Sub
End Class

For more information, see:


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:

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

Expand table
Is datatype present Is counter already Result (whether counter defines a new local variable
? defined? 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
Is datatype present Is counter already Result (whether counter defines a new local variable
? defined? that’s scoped to the entire For...Next loop)
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, Si


ngle, 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.

Example 1
The following example removes all elements from a generic list. Instead of
a For Each...Next Statement, the example shows a For...Next statement that
iterates in descending order. The example uses this technique because
the removeAt method causes elements after the removed element to have a
lower index value.

VBCopy
Dim lst As New List(Of Integer) From {10, 20, 30, 40}
For index As Integer = lst.Count - 1 To 0 Step -1
lst.RemoveAt(index)
Next

Debug.WriteLine(lst.Count.ToString)
' Output: 0

Example 2
The following example iterates through an enumeration that's declared by
using an Enum Statement.

VBCopy
Public Enum Mammals
Buffalo
Gazelle
Mongoose
Rhinoceros
Whale
End Enum

Public Sub ListSomeMammals()


For mammal As Mammals = Mammals.Gazelle To Mammals.Rhinoceros
Debug.Write(mammal.ToString & " ")
Next
Debug.WriteLine("")
' Output: Gazelle Mongoose Rhinoceros
End Sub

Example 3
In the following example, the statement parameters use a class that has
operator overloads for the +, -, >=, and <= operators.

VBCopy
Private Class Distance
Public Property Number() As Double

Public Sub New(ByVal number As Double)


Me.Number = number
End Sub

' Define operator overloads to support For...Next statements.


Public Shared Operator +(ByVal op1 As Distance, ByVal op2 As Distance) As
Distance
Return New Distance(op1.Number + op2.Number)
End Operator
Public Shared Operator -(ByVal op1 As Distance, ByVal op2 As Distance) As
Distance
Return New Distance(op1.Number - op2.Number)
End Operator

Public Shared Operator >=(ByVal op1 As Distance, ByVal op2 As Distance)


As Boolean
Return (op1.Number >= op2.Number)
End Operator

Public Shared Operator <=(ByVal op1 As Distance, ByVal op2 As Distance)


As Boolean
Return (op1.Number <= op2.Number)
End Operator
End Class

Public Sub ListDistances()


Dim distFrom As New Distance(10)
Dim distTo As New Distance(25)
Dim distStep As New Distance(4)

For dist As Distance = distFrom To distTo Step distStep


Debug.Write(dist.Number.ToString & " ")
Next
Debug.WriteLine("")

' Output: 10 14 18 22
End Sub

You might also like