Fedt Notes
Fedt Notes
Net - Overview
[Link] is a simple, modern, object-oriented computer programming language developed by Microsoft to
combine the power of .NET Framework and the common language runtime with the productivity benefits that
are the hallmark of Visual Basic. This tutorial will teach you basic [Link] programming and will also take you
through various advanced concepts related to [Link] programming language.
Let us look at a simple code that would print the words "Hello World" −
Imports System
Module Module1
'This program will display Hello World
Sub Main()
[Link]("Hello World")
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Hello, World!
'Public methods
Public Sub AcceptDetails()
length = 4.5
width = 3.5
End Sub
End Sub
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The
basic rules for naming classes in [Link] are as follows −
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or
underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \.
However, an underscore ( _ ) can be used.
It should not be a reserved keyword.
[Link] Keywords
The following table lists the [Link] reserved keywords −
Double 8 bytes
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative
values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values
Single 4 bytes
-3.4028235E+38 through -1.401298E-45 for
negative values;
1.401298E-45 through 3.4028235E+38 for
positive values
User- Depends on implementing platform Each member of the structure has a range
Defined determined by its data type and independent of the
ranges of the other members
UShort 2 bytes 0 through 65,535 (unsigned)
Example
The following example demonstrates use of some of the types −
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean
b=1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"
If bl Then
'the oath taking
[Link](c & " and," & s & vbCrLf)
[Link]("declaring on the day of: {0}", da)
[Link]("We will learn [Link] seriously")
[Link]("Lets see what happens to the floating point variables:")
[Link]("The Single: {0}, The Double: {1}", si, d)
End If
[Link]()
End Sub
End Module
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn [Link] seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346
The Type Conversion Functions in [Link]
[Link] provides the following in-line type conversion functions −
1
CBool(expression)
Converts the expression to Boolean data type.
2
CByte(expression)
Converts the expression to Byte data type.
3
CChar(expression)
Converts the expression to Char data type.
4
CDate(expression)
Converts the expression to Date data type
5
CDbl(expression)
Converts the expression to Double data type.
6
CDec(expression)
Converts the expression to Decimal data type.
7
CInt(expression)
Converts the expression to Integer data type.
8
CLng(expression)
Converts the expression to Long data type.
9
CObj(expression)
Converts the expression to Object type.
10
CSByte(expression)
Converts the expression to SByte data type.
11
CShort(expression)
Converts the expression to Short data type.
12
CSng(expression)
Converts the expression to Single data type.
13
CStr(expression)
Converts the expression to String data type.
14
CUInt(expression)
Converts the expression to UInt data type.
15
CULng(expression)
Converts the expression to ULng data type.
16
CUShort(expression)
Converts the expression to UShort data type.
Example
The following example demonstrates some of these functions −
Module DataTypes
Sub Main()
Dim n As Integer
Dim da As Date
Dim bl As Boolean = True
n = 1234567
da = Today
[Link](bl)
[Link](CSByte(bl))
[Link](CStr(bl))
[Link](CStr(da))
[Link](CChar(CChar(CStr(n))))
[Link](CChar(CStr(da)))
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
True
-1
True
12/4/2012
1
1
[Link] - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in [Link] has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
We have already discussed various data types. The basic value types provided in [Link] can be
categorized as −
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
[Link] also allows defining other value types of variable like Enum and reference types of variables
like Class. We will discuss date types and Classes in subsequent chapters.
Example
Try the following example which makes use of various types of variables −
Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c=a+b
[Link]("a = {0}, b = {1}, c = {2}", a, b, c)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
Declaring Constants
In [Link], constants are declared using the Const statement. The Const statement is used at module,
class, structure, procedure, or block level for use in place of literal values.
The syntax for the Const statement is −
[ < attributelist > ] [ accessmodifier ] [ Shadows ]
Const constantlist
Where,
attributelist − specifies the list of attributes applied to the constants; you can provide multiple
attributes separated by commas. Optional.
accessmodifier − specifies which code can access these constants. Optional. Values can be
either of the: Public, Protected, Friend, Protected Friend, or Private.
Shadows − this makes the constant hide a programming element of identical name in a base
class. Optional.
Constantlist − gives the list of names of constants declared. Required.
Where, each constant name has the following syntax and parts −
constantname [ As datatype ] = initializer
constantname − specifies the name of the constant
datatype − specifies the data type of the constant
initializer − specifies the value assigned to the constant
For example,
'The following statements declare constants.'
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415
Example
The following example demonstrates declaration and use of a constant value −
Module constantsNenum
Sub Main()
Const PI = 3.14149
Dim radius, area As Single
radius = 7
area = PI * radius * radius
[Link]("Area = " & Str(area))
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Area = 153.933
1
vbCrLf
Carriage return/linefeed character combination.
2
vbCr
Carriage return character.
3
vbLf
Linefeed character.
4
vbNewLine
Newline character.
5
vbNullChar
Null character.
6
vbNullString
Not the same as a zero-length string (""); used for calling external procedures.
7
vbObjectError
Error number. User-defined error numbers should be greater than this value. For example:
[Link](Number) = vbObjectError + 1000
8
vbTab
Tab character.
9
vbBack
Backspace character.
Declaring Enumerations
An enumerated type is declared using the Enum statement. The Enum statement declares an
enumeration and defines the values of its members. The Enum statement can be used at the module,
class, structure, procedure, or block level.
The syntax for the Enum statement is as follows −
[ < attributelist > ] [ accessmodifier ] [ Shadows ]
Enum enumerationname [ As datatype ]
memberlist
End Enum
Where,
attributelist − refers to the list of attributes applied to the variable. Optional.
accessmodifier − specifies which code can access these enumerations. Optional. Values can
be either of the: Public, Protected, Friend or Private.
Shadows − this makes the enumeration hide a programming element of identical name in a
base class. Optional.
enumerationname − name of the enumeration. Required
datatype − specifies the data type of the enumeration and all its members.
memberlist − specifies the list of member constants being declared in this statement. Required.
Each member in the memberlist has the following syntax and parts:
[< attribute list >] member name [ = initializer ]
Where,
name − specifies the name of the member. Required.
initializer − value assigned to the enumeration member. Optional.
For example,
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Example
The following example demonstrates declaration and use of the Enum variable Colors −
Module constantsNenum
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Sub Main()
[Link]("The Color Red is : " & [Link])
[Link]("The Color Yellow is : " & [Link])
[Link]("The Color Blue is : " & [Link])
[Link]("The Color Green is : " & [Link])
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
The Color Red is: 1
The Color Yellow is: 3
The Color Blue is: 6
The Color Green is: 4
[Link] - Modifiers
The modifiers are keywords added with any programming element to give some especial emphasis on
how the programming element will behave or will be accessed in the program.
For example, the access modifiers: Public, Private, Protected, Friend, Protected Friend, etc., indicate
the access level of a programming element like a variable, constant, enumeration or a class.
2 Assembly Specifies that an attribute at the beginning of a source file applies to the
entire assembly.
4 Auto The charsetmodifier part in the Declare statement supplies the character
set information for marshaling strings during a call to the external
procedure. It also affects how Visual Basic searches the external file for
the external procedure name. The Auto modifier specifies that Visual Basic
should marshal strings according to .NET Framework rules.
6 ByVal Specifies that an argument is passed in such a way that the called
procedure or property cannot change the value of a variable underlying the
argument in the calling code. It is used under the contexts of −
Declare Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
8 Friend
Specifies that one or more declared programming elements are
accessible from within the assembly that contains their declaration, not
only by the component that declares them.
Friend access is often the preferred level for an application's
programming elements, and Friend is the default access level of an
interface, a module, a class, or a structure.
11 Key The Key keyword enables you to specify behavior for properties of
anonymous types.
12 Module Specifies that an attribute at the beginning of a source file applies to the
current assembly module. It is not same as the Module statement.
13 MustInherit Specifies that a class can be used only as a base class and that you
cannot create an object directly from it.
14 MustOverride Specifies that a property or procedure is not implemented in this class and
must be overridden in a derived class before it can be used.
18 Optional Specifies that a procedure argument can be omitted when the procedure is
called.
19 Out For generic type parameters, the Out keyword specifies that the type is
covariant.
25 Private Specifies that one or more declared programming elements are accessible
only from within their declaration context, including from within any
contained types.
26 Protected Specifies that one or more declared programming elements are accessible
only from within their own class or from a derived class.
27 Public Specifies that one or more declared programming elements have no
access restrictions.
28 ReadOnly Specifies that a variable or property can be read but not written.
30 Shared Specifies that one or more declared programming elements are associated
with a class or structure at large, and not with a specific instance of the
class or structure.
31 Static Specifies that one or more declared local variables are to continue to exist
and retain their latest values after termination of the procedure in which
they are declared.
32 Unicode Specifies that Visual Basic should marshal all strings to Unicode values
regardless of the name of the external procedure being declared.
34 WithEvents Specifies that one or more declared member variables refer to an instance
of a class that can raise events.
[Link] - Statements
A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators,
variables, literal values, constants and expressions.
Statements could be categorized as −
Declaration statements − these are the statements where you name a variable, constant, or
procedure, and can also specify a data type.
Executable statements − these are the statements, which initiate actions. These statements
can call a method or function, loop or branch through blocks of code or assign values or
expression to a variable or constant. In the last case, it is called an Assignment statement.
Declaration Statements
The declaration statements are used to name and define procedures, variables, properties, arrays,
and constants. When you declare a programming element, you can also define its data type, access
level, and scope.
The programming elements you may declare include variables, constants, enumerations, classes,
structures, modules, interfaces, procedures, procedure parameters, function returns, external
procedure references, operators, properties, events, and delegates.
Following are the declaration statements in [Link] −
[Link] Statements and Description Example
3 Enum CoffeeMugSize
Enum Statement
Jumbo
Declares an enumeration and defines the values of its ExtraLarge
Large
members. Medium
Small
End Enum
4 Class Box
Class Statement
Public length As Double
Declares the name of a class and introduces the definition of Public breadth As Double
Public height As Double
the variables, properties, events, and procedures that the class
End Class
comprises.
5 Structure Box
Structure Statement
Public length As Double
Declares the name of a structure and introduces the definition Public breadth As Double
Public height As Double
of the variables, properties, events, and procedures that the
End Structure
structure comprises.
8 Function myFunction
Function Statement
(ByVal n As Integer) As Double
Declares the name, parameters, and code that define a Return 5.87 * n
End Function
Function procedure.
9 Sub mySub(ByVal s As String)
Sub Statement
Return
Declares the name, parameters, and code that define a Sub End Sub
procedure.
Executable Statements
An executable statement performs an action. Statements calling a procedure, branching to another
place in the code, looping through several statements, or evaluating an expression are executable
statements. An assignment statement is a special case of an executable statement.
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10
[Link] - Directives
The [Link] compiler directives give instructions to the compiler to preprocess the information before
actual compilation starts. All these directives begin with #, and only white-space characters may
appear before a directive on a line. These directives are not statements.
[Link] compiler does not have a separate preprocessor; however, the directives are processed as if
there was one. In [Link], the compiler directives are used to help in conditional compilation. Unlike C
and C++ directives, they are not used to create macros.
Sub TestExternalSource()
#ExternalSource("c:\vbprogs\[Link]", 5)
[Link]("This is External Code. ")
#End ExternalSource
End Sub
End Class
Sub Main()
Dim t As New ExternalSourceTester()
[Link]()
[Link]("In Main.")
[Link]()
End Sub
When the above code is compiled and executed, it produces the following result −
This is External Code.
In Main.
The #If...Then...#Else Directives
This directive conditionally compiles selected blocks of Visual Basic code.
Syntax for this directive is −
#If expression Then
statements
[ #ElseIf expression Then
[ statements ]
...
#ElseIf expression Then
[ statements ] ]
[ #Else
[ statements ] ]
#End If
For example,
#Const TargetOS = "Linux"
#If TargetOS = "Windows 7" Then
' Windows 7 specific code
#ElseIf TargetOS = "WinXP" Then
' Windows XP specific code
#Else
' Code for other OS
#End if
Example
The following code demonstrates a hypothetical use of the directive −
Live Demo
Module mydirectives
#Const classCode = 8
Sub Main()
#If classCode = 7 Then
[Link]("Exam Questions for Class VII")
#ElseIf classCode = 8 Then
[Link]("Exam Questions for Class VIII")
#Else
[Link]("Exam Questions for Higher Classes")
#End If
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Exam Questions for Class VIII
The #Region Directive
This directive helps in collapsing and hiding sections of code in Visual Basic files.
Syntax for this directive is −
#Region "identifier_string"
#End Region
For example,
#Region "StatsFunctions"
' Insert code for the Statistical functions here.
#End Region
[Link] - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. [Link] is rich in built-in operators and provides following types of commonly used
operators −
Arithmetic Operators
Comparison Operators
Logical/Bitwise Operators
Bit Shift Operators
Assignment Operators
Miscellaneous Operators
This tutorial will explain the most commonly used operators.
Arithmetic Operators
Following table shows all the arithmetic operators supported by [Link]. Assume variable A holds 2
and variable B holds 7, then −
/ Divides one operand by another and returns a floating point B / A will give 3.5
result
\ Divides one operand by another and returns an integer result B \ A will give 3
MOD Modulus Operator and remainder of after an integer division B MOD A will give 1
Comparison Operators
Following table shows all the comparison operators supported by [Link]. Assume variable A holds 10
and variable B holds 20, then −
= Checks if the values of two operands are equal or not; if yes, then (A = B) is not true.
condition becomes true.
<> Checks if the values of two operands are equal or not; if values are not (A <> B) is true.
equal, then condition becomes true.
> Checks if the value of left operand is greater than the value of right (A > B) is not true.
operand; if yes, then condition becomes true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand; if yes, then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value (A >= B) is not
of right operand; if yes, then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is true.
right operand; if yes, then condition becomes true.
Apart from the above, [Link] provides three more comparison operators, which we will be using in
forthcoming chapters; however, we give a brief description here.
Is Operator − It compares two object reference variables and determines if two object
references refer to the same object without performing value comparisons. If object1 and
object2 both refer to the exact same object instance, result is True; otherwise, result is False.
IsNot Operator − It also compares two object reference variables and determines if two object
references refer to different objects. If object1 and object2 both refer to the exact same object
instance, result is False; otherwise, result is True.
Like Operator − It compares a string against a pattern.
Logical/Bitwise Operators
Following table shows all the logical operators supported by [Link]. Assume variable A holds Boolean
value True and variable B holds Boolean value False, then −
Operator Description Example
And It is the logical as well as bitwise AND operator. If both the operands are (A And B) is
true, then condition becomes true. This operator does not perform short- False.
circuiting, i.e., it evaluates both the expressions.
Not It is the logical as well as bitwise NOT operator. Use to reverses the logical Not(A And
state of its operand. If a condition is true, then Logical NOT operator will B) is True.
make false.
Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns A Xor B is
True if both expressions are True or both expressions are False; otherwise True.
it returns False. This operator does not perform short-circuiting, it always
evaluates both expressions and there is no short-circuiting counterpart of
this operator.
AndAlso It is the logical AND operator. It works only on Boolean data. It performs (A AndAlso
short-circuiting. B) is False.
OrElse It is the logical OR operator. It works only on Boolean data. It performs (A OrElse
short-circuiting. B) is True.
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
We have seen that the Bitwise operators supported by [Link] are And, Or, Xor and Not. The Bit shift
operators are >> and << for left shift and right shift, respectively.
Assume that the variable A holds 60 and variable B holds 13, then −
And Bitwise AND Operator copies a bit to the result if it exists in both (A AND B) will give 12,
operands. which is 0000 1100
Or Binary OR Operator copies a bit if it exists in either operand. (A Or B) will give 61,
which is 0011 1101
Xor Binary XOR Operator copies the bit if it is set in one operand but (A Xor B) will give 49,
not both. which is 0011 0001
Not Binary Ones Complement Operator is unary and has the effect (Not A ) will give -61,
of 'flipping' bits. which is 1100 0011 in 2's
complement form due to a
signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left A << 2 will give 240, which
by the number of bits specified by the right operand. is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 will give 15, which
right by the number of bits specified by the right operand. is 0000 1111
Assignment Operators
There are following assignment operators supported by [Link] −
= Simple assignment operator, Assigns values from right side C = A + B will assign value
operands to left side operand of A + B into C
+= Add AND assignment operator, It adds right operand to the left C += A is equivalent to C =
operand and assigns the result to left operand C+A
Miscellaneous Operators
There are few other important operators supported by [Link].
GetType It returns a Type object for the specified type. The MsgBox(GetType(Integer).ToString())
Type object provides information about the type
such as its properties, methods, and events.
Function It declares the parameters and code that define a Dim add5 = Function(num As
Expression function lambda expression. Integer) num + 5
'prints 10
[Link](add5(5))
Operator Precedence
Await Highest
Exponentiation (^)
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Negation (Not)
[Link] provides the following types of decision making statements. Click the following links to check
their details.
Statement Description
Select Case statement A Select Case statement allows a variable to be tested for equality
against a list of values.
nested Select Case statements You can use one select case statement inside another select
case statement(s).
Flow Diagram
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 10
Syntax
The syntax of an If...Then... Else statement in [Link] is as follows −
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If
If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else
block of code will be executed.
Flow Diagram
Example
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
Syntax
The syntax of an if...else if...else statement in [Link] is as follows −
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If
Example
Live Demo
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
' check the boolean condition '
If (a = 10) Then
' if condition is true then print the following '
[Link]("Value of a is 10") '
ElseIf (a = 20) Then
'if else if condition is true '
[Link]("Value of a is 20") '
ElseIf (a = 30) Then
'if else if condition is true
[Link]("Value of a is 30")
Else
'if none of the conditions is true
[Link]("None of the values is matching")
End If
[Link]("Exact value of a is: {0}", a)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
None of the values is matching
Exact value of a is: 100
[Link] - Nested If Statements
It is always legal in [Link] to nest If-Then-Else statements, which means you can use one If or ElseIf
statement inside another If ElseIf statement(s).
Syntax
The syntax for a nested If statement is as follows −
If( boolean_expression 1)Then
'Executes when the boolean expression 1 is true
If(boolean_expression 2)Then
'Executes when the boolean expression 2 is true
End If
End If
You can nest ElseIf...Else in the similar way as you have nested If statement.
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
' check the boolean condition
If (a = 100) Then
' if condition is true then check the following
If (b = 200) Then
' if condition is true then print the following
[Link]("Value of a is 100 and b is 200")
End If
End If
[Link]("Exact value of a is : {0}", a)
[Link]("Exact value of b is : {0}", b)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
It is always legal in [Link] to nest If-Then-Else statements, which means you can use one If or ElseIf
statement inside another If ElseIf statement(s).
Syntax
The syntax for a nested If statement is as follows −
If( boolean_expression 1)Then
'Executes when the boolean expression 1 is true
If(boolean_expression 2)Then
'Executes when the boolean expression 2 is true
End If
End If
You can nest ElseIf...Else in the similar way as you have nested If statement.
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
' check the boolean condition
If (a = 100) Then
' if condition is true then check the following
If (b = 200) Then
' if condition is true then print the following
[Link]("Value of a is 100 and b is 200")
End If
End If
[Link]("Exact value of a is : {0}", a)
[Link]("Exact value of b is : {0}", b)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
[Link] - Select Case Statement
A Select Case statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each select case.
Syntax
The syntax for a Select Case statement in [Link] is as follows −
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
expression − is an expression that must evaluate to any of the elementary data type in [Link],
i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single,
String, UInteger, ULong, and UShort.
expressionlist − List of expression clauses representing match values for expression. Multiple
expression clauses are separated by commas.
statements − statements following Case that run if the select expression matches any clause
in expressionlist.
elsestatements − statements following Case Else that run if the select expression does not
match any clause in the expressionlist of any of the Case statements.
Flow Diagram
Example
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
[Link]("Excellent!")
Case "B", "C"
[Link]("Well done")
Case "D"
[Link]("You passed")
Case "F"
[Link]("Better try again")
Case Else
[Link]("Invalid grade")
End Select
[Link]("Your grade is {0}", grade)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
[Link] - Nested Select Case Statement
It is possible to have a select statement as part of the statement sequence of an outer select
statement. Even if the case constants of the inner and outer select contain common values, no
conflicts will arise.
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Select a
Case 100
[Link]("This is part of outer case ")
Select Case b
Case 200
[Link]("This is part of inner case ")
End Select
End Select
[Link]("Exact value of a is : {0}", a)
[Link]("Exact value of b is : {0}", b)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
This is part of outer case
This is part of inner case
Exact value of a is : 100
Exact value of b is : 200
[Link] - Loops
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and following
is the general form of a loop statement in most of the programming languages −
[Link] provides following types of loops to handle looping requirements. Click the following links to
check their details.
With... End With It is not exactly a looping construct. It executes a series of statements that
repeatedly refer to a single object or structure.
Nested loops You can use one or more loops inside any another While, For or Do loop.
[Link] - Do Loop
It repeats the enclosed block of statements while a Boolean condition is True or until the condition
becomes True. It could be terminated at any time with the Exit Do statement.
The syntax for this loop construct is −
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
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
[Link]("value of a: {0}", a)
a=a+1
Loop While (a < 20)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
The program would behave in same way, if you use an Until statement, instead of While −
Live Demo
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
[Link]("value of a: {0}", a)
a=a+1
Loop Until (a = 20)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
[Link] - For...Next Loop
It repeats a group of statements a specified number of times and a loop index counts the number of
loop iterations as the loop executes.
The syntax for this loop construct is −
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
Flow Diagram
Example
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
[Link]("value of a: {0}", a)
Next
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
If you want to use a step size of 2, for example, you need to display only even numbers, between 10
and 20 −
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20 Step 2
[Link]("value of a: {0}", a)
Next
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 12
value of a: 14
value of a: 16
value of a: 18
value of a: 20
[Link] - Each...Next Loop
It repeats a group of statements for each element in a collection. This loop is used for accessing and
manipulating all elements in an array or a [Link] collection.
The syntax for this loop construct is −
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
Example
Module loops
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
'displaying the values
Flow Diagram
Here, key point of the While loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example
Module loops
Sub Main()
Dim a As Integer = 10
' while loop execution '
While a < 20
[Link]("value of a: {0}", a)
a=a+1
End While
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
[Link] - With... End With Statement
It is not exactly a looping construct. It executes a series of statements that repeatedly refers to a single
object or structure.
The syntax for this loop construct is −
With object
[ statements ]
End With
Example
Module loops
Public Class Book
Public Property Name As String
Public Property Author As String
Public Property Subject As String
End Class
Sub Main()
Dim aBook As New Book
With aBook
.Name = "[Link] Programming"
.Author = "Zara Ali"
.Subject = "Information Technology"
End With
With aBook
[Link](.Name)
[Link](.Author)
[Link](.Subject)
End With
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
[Link] Programming
Zara Ali
Information Technology
[Link] - Nested Loops
[Link] allows using one loop inside another loop. Following section shows few examples to illustrate
the concept.
Syntax
The syntax for a nested For loop statement in [Link] is as follows −
For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ]
For counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ]
...
Next [ counter2 ]
Next [ counter 1]
The syntax for a nested While loop statement in [Link] is as follows −
While condition1
While condition2
...
End While
End While
The syntax for a nested Do...While loop statement in [Link] is as follows −
Do { While | Until } condition1
Do { While | Until } condition2
...
Loop
Loop
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For
example, a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Module loops
Sub Main()
' local variable definition
Dim i, j As Integer
For i = 2 To 100
For j = 2 To i
' if factor found, not prime
If ((i Mod j) = 0) Then
Exit For
End If
Next j
If (j > (i \ j)) Then
[Link]("{0} is prime", i)
End If
Next i
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
Syntax
The syntax for the Exit statement is −
Exit { Do | For | Function | Property | Select | Sub | Try | While }
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
' while loop execution '
Syntax
The syntax for a Continue statement is as follows −
Continue { Do | For | While }
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
Do
If (a = 15) Then
' skip the iteration '
a=a+1
Continue Do
End If
[Link]("value of a: {0}", a)
a=a+1
Loop While (a < 20)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
[Link] - GoTo Statement
The GoTo statement transfers control unconditionally to a specified line in a procedure.
The syntax for the GoTo statement is −
GoTo label
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
Line1:
Do
If (a = 15) Then
' skip the iteration '
a=a+1
GoTo Line1
End If
[Link]("value of a: {0}", a)
a=a+1
Loop While (a < 20)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
[Link] - Strings
In [Link], you can use strings as array of characters, however, more common practice is to use the
String keyword to declare a string variable. The string keyword is an alias for the [Link] class.
1
Chars
Gets the Char object at a specified position in the current String object.
2
Length
Gets the number of characters in the current String object.
1
Public Shared Function Compare ( strA As String, strB As String ) As Integer
Compares two specified string objects and returns an integer that indicates their relative
position in the sort order.
2
Public Shared Function Compare ( strA As String, strB As String, ignoreCase As
Boolean ) As Integer
Compares two specified string objects and returns an integer that indicates their relative
position in the sort order. However, it ignores case if the Boolean parameter is true.
3
Public Shared Function Concat ( str0 As String, str1 As String ) As String
Concatenates two string objects.
4
Public Shared Function Concat ( str0 As String, str1 As String, str2 As String ) As
String
Concatenates three string objects.
5
Public Shared Function Concat (str0 As String, str1 As String, str2 As String, str3 As
String ) As String
Concatenates four string objects.
6
Public Function Contains ( value As String ) As Boolean
Returns a value indicating whether the specified string object occurs within this string.
7
Public Shared Function Copy ( str As String ) As String
Creates a new String object with the same value as the specified string.
8
pPublic Sub CopyTo ( sourceIndex As Integer, destination As Char(), destinationIndex
As Integer, count As Integer )
Copies a specified number of characters from a specified position of the string object to a
specified position in an array of Unicode characters.
9
Public Function EndsWith ( value As String ) As Boolean
Determines whether the end of the string object matches the specified string.
10
Public Function Equals ( value As String ) As Boolean
Determines whether the current string object and the specified string object have the same
value.
11
Public Shared Function Equals ( a As String, b As String ) As Boolean
Determines whether two specified string objects have the same value.
12
Public Shared Function Format ( format As String, arg0 As Object ) As String
Replaces one or more format items in a specified string with the string representation of a
specified object.
13
Public Function IndexOf ( value As Char ) As Integer
Returns the zero-based index of the first occurrence of the specified Unicode character in the
current string.
14
Public Function IndexOf ( value As String ) As Integer
Returns the zero-based index of the first occurrence of the specified string in this instance.
15
Public Function IndexOf ( value As Char, startIndex As Integer ) As Integer
Returns the zero-based index of the first occurrence of the specified Unicode character in this
string, starting search at the specified character position.
16
Public Function IndexOf ( value As String, startIndex As Integer ) As Integer
Returns the zero-based index of the first occurrence of the specified string in this instance,
starting search at the specified character position.
17
Public Function IndexOfAny ( anyOf As Char() ) As Integer
Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters.
18
Public Function IndexOfAny ( anyOf As Char(), startIndex As Integer ) As Integer
Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters, starting search at the specified character position.
19
Public Function Insert ( startIndex As Integer, value As String ) As String
Returns a new string in which a specified string is inserted at a specified index position in the
current string object.
20
Public Shared Function IsNullOrEmpty ( value As String ) As Boolean
Indicates whether the specified string is null or an Empty string.
21
Public Shared Function Join ( separator As String, ParamArray value As String() ) As
String
Concatenates all the elements of a string array, using the specified separator between each
element.
22
Public Shared Function Join ( separator As String, value As String(), startIndex As
Integer, count As Integer ) As String
Concatenates the specified elements of a string array, using the specified separator between
each element.
23
Public Function LastIndexOf ( value As Char ) As Integer
Returns the zero-based index position of the last occurrence of the specified Unicode
character within the current string object.
24
Public Function LastIndexOf ( value As String ) As Integer
Returns the zero-based index position of the last occurrence of a specified string within the
current string object.
25
Public Function Remove ( startIndex As Integer ) As String
Removes all the characters in the current instance, beginning at a specified position and
continuing through the last position, and returns the string.
26
Public Function Remove ( startIndex As Integer, count As Integer ) As String
Removes the specified number of characters in the current string beginning at a specified
position and returns the string.
27
Public Function Replace ( oldChar As Char, newChar As Char ) As String
Replaces all occurrences of a specified Unicode character in the current string object with the
specified Unicode character and returns the new string.
28
Public Function Replace ( oldValue As String, newValue As String ) As String
Replaces all occurrences of a specified string in the current string object with the specified
string and returns the new string.
29
Public Function Split ( ParamArray separator As Char() ) As String()
Returns a string array that contains the substrings in the current string object, delimited by
elements of a specified Unicode character array.
30
Public Function Split ( separator As Char(), count As Integer ) As String()
Returns a string array that contains the substrings in the current string object, delimited by
elements of a specified Unicode character array. The int parameter specifies the maximum
number of substrings to return.
31
Public Function StartsWith ( value As String ) As Boolean
Determines whether the beginning of this string instance matches the specified string.
32
Public Function ToCharArray As Char()
Returns a Unicode character array with all the characters in the current string object.
33
Public Function ToCharArray ( startIndex As Integer, length As Integer ) As Char()
Returns a Unicode character array with all the characters in the current string object, starting
from the specified index and up to the specified length.
34
Public Function ToLower As String
Returns a copy of this string converted to lowercase.
35
Public Function ToUpper As String
Returns a copy of this string converted to uppercase.
36
Public Function Trim As String
Removes all leading and trailing white-space characters from the current String object.
The above list of methods is not exhaustive, please visit MSDN library for the complete list of methods
and String class constructors.
Examples
The following example demonstrates some of the methods mentioned above −
Comparing Strings
Module strings
Sub Main()
Dim str1, str2 As String
str1 = "This is test"
str2 = "This is text"
If ([Link]("test")) Then
[Link]("The sequence 'test' was found.")
End If
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
The sequence 'test' was found.
Getting a Substring:
Module strings
Sub Main()
Dim str As String
str = "Last night I dreamt of San Pedro"
[Link](str)
Note:
Both the DateTime structure and the DateAndTime module contain properties
like Now and Today, so often beginners find it confusing. The DateAndTime class belongs to the
[Link] namespace and the DateTime structure belongs to the System namespace.
Therefore, using the later would help you in porting your code to another .Net language like C#.
However, the DateAndTime class/module contains all the legacy date functions available in Visual
Basic.
6 Kind Gets a value that indicates whether the time represented by this
instance is based on local time, Coordinated Universal Time (UTC),
or neither.
10 Now Gets a DateTime object that is set to the current date and time on
this computer, expressed as the local time.
12 Ticks Gets the number of ticks that represent the date and time of this
instance.
15 UtcNow Gets a DateTime object that is set to the current date and time on
this computer, expressed as the Coordinated Universal Time
(UTC).
16 Year Gets the year component of the date represented by this instance.
The following table lists some of the commonly used methods of the DateTime structure −
2
Public Function AddDays ( value As Double) As DateTime
Returns a new DateTime that adds the specified number of days to the value of this
instance.
3
Public Function AddHours (value As Double) As DateTime
Returns a new DateTime that adds the specified number of hours to the value of this
instance.
4
Public Function AddMinutes (value As Double) As DateTime
Returns a new DateTime that adds the specified number of minutes to the value of this
instance.
5
Public Function AddMonths (months As Integer) As DateTime
Returns a new DateTime that adds the specified number of months to the value of this
instance.
6
Public Function AddSeconds (value As Double) As DateTime
Returns a new DateTime that adds the specified number of seconds to the value of
this instance.
7
Public Function AddYears (value As Integer ) As DateTime
Returns a new DateTime that adds the specified number of years to the value of this
instance.
8
Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer
Compares two instances of DateTime and returns an integer that indicates whether
the first instance is earlier than, the same as, or later than the second instance.
9
Public Function CompareTo (value As DateTime) As Integer
Compares the value of this instance to a specified DateTime value and returns an
integer that indicates whether this instance is earlier than, the same as, or later than
the specified DateTime value.
10
Public Function Equals (value As DateTime) As Boolean
Returns a value indicating whether the value of this instance is equal to the value of
the specified DateTime instance.
11
Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean
Returns a value indicating whether two DateTime instances have the same date and
time value.
12
Public Overrides Function ToString As String
Converts the value of the current DateTime object to its equivalent string
representation.
The above list of methods is not exhaustive, please visit Microsoft documentation for the complete list
of methods and properties of the DateTime structure.
[Link](date1)
[Link](date2)
[Link](date3)
[Link](date4)
[Link](date5)
[Link]()
End Sub
End Module
When the above code was compiled and executed, it produces the following result −
12/16/2012 12:00:00 PM
12/16/2012 12:00:52 PM
12/12/2012 10:22:50 PM
12/12/2012 12:00:00 PM
Formatting Date
A Date literal should be enclosed within hash signs (# #), and specified in the format M/d/yyyy, for
example #12/16/2012#. Otherwise, your code may change depending on the locale in which your
application is running.
For example, you specified Date literal of #2/6/2012# for the date February 6, 2012. It is alright for the
locale that uses mm/dd/yyyy format. However, in a locale that uses dd/mm/yyyy format, your literal
would compile to June 2, 2012. If a locale uses another format say, yyyy/mm/dd, the literal would be
invalid and cause a compiler error.
To convert a Date literal to the format of your locale or to a custom format, use the Format function of
String class, specifying either a predefined or user-defined date format.
The following example demonstrates this.
Module dateNtime
Sub Main()
[Link]("India Wins Freedom: ")
Dim independenceDay As New Date(1947, 8, 15, 0, 0, 0)
' Use format specifiers to control the date display.
[Link](" Format 'd:' " & [Link]("d"))
[Link](" Format 'D:' " & [Link]("D"))
[Link](" Format 't:' " & [Link]("t"))
[Link](" Format 'T:' " & [Link]("T"))
[Link](" Format 'f:' " & [Link]("f"))
[Link](" Format 'F:' " & [Link]("F"))
[Link](" Format 'g:' " & [Link]("g"))
[Link](" Format 'G:' " & [Link]("G"))
[Link](" Format 'M:' " & [Link]("M"))
[Link](" Format 'R:' " & [Link]("R"))
[Link](" Format 'y:' " & [Link]("y"))
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
India Wins Freedom:
Format 'd:' 8/15/1947
Format 'D:' Friday, August 15, 1947
Format 't:' 12:00 AM
Format 'T:' 12:00:00 AM
Format 'f:' Friday, August 15, 1947 12:00 AM
Format 'F:' Friday, August 15, 1947 12:00:00 AM
Format 'g:' 8/15/1947 12:00 AM
Format 'G:' 8/15/1947 12:00:00 AM
Format 'M:' 8/15/1947 August 15
Format 'R:' Fri, 15 August 1947 00:00:00 GMT
Format 'y:' August, 1947
Format Description
General Date, or G Displays a date and/or time. For example, 1/12/2012 07:07:30 AM.
Long Date,Medium Date, or D Displays a date according to your current culture's long date format.
For example, Sunday, December 16, 2012.
Short Date, or d Displays a date using your current culture's short date format. For
example, 12/12/2012.
Long Time,Medium Time, orT Displays a time using your current culture's long time format; typically
includes hours, minutes, seconds. For example, 01:07:30 AM.
Short Time or t Displays a time using your current culture's short time format. For
example, 11:07 AM.
f Displays the long date and short time according to your current
culture's format. For example, Sunday, December 16, 2012 12:15 AM.
F Displays the long date and long time according to your current culture's
format. For example, Sunday, December 16, 2012 12:15:31 AM.
g Displays the short date and short time according to your current
culture's format. For example, 12/16/2012 12:15 AM.
M, m Displays the month and the day of a date. For example, December 16.
s Formats the date and time as a sortable index. For example, 2012-12-
16T12:07:31.
u Formats the date and time as a GMT sortable index. For example,
2012-12-16 12:15:31Z.
U Formats the date and time with the long date and long time as GMT.
For example, Sunday, December 16, 2012 6:07:31 PM.
Y, y Formats the date as the year and month. For example, December,
2012.
For other formats like user-defined formats, please consult Microsoft Documentation.
1
Date
Returns or sets a String value representing the current date according to
your system.
2
Now
Returns a Date value containing the current date and time according to your
system.
3
TimeOfDay
Returns or sets a Date value containing the current time of day according to
your system.
4
Timer
Returns a Double value representing the number of seconds elapsed since
midnight.
5
TimeString
Returns or sets a String value representing the current time of day
according to your system.
6
Today
Gets the current date.
The following table lists some of the commonly used methods of the DateAndTime class −
1
Public Shared Function DateAdd (Interval As DateInterval, Number As
Double, DateValue As DateTime) As DateTime
Returns a Date value containing a date and time value to which a specified
time interval has been added.
2
Public Shared Function DateAdd (Interval As String,Number As
Double,DateValue As Object ) As DateTime
Returns a Date value containing a date and time value to which a specified
time interval has been added.
3
Public Shared Function DateDiff (Interval As DateInterval, Date1 As
DateTime, Date2 As DateTime, DayOfWeek As FirstDayOfWeek,
WeekOfYear As FirstWeekOfYear ) As Long
Returns a Long value specifying the number of time intervals between two
Date values.
4
Public Shared Function DatePart (Interval As DateInterval, DateValue
As DateTime, FirstDayOfWeekValue As FirstDayOfWeek,
FirstWeekOfYearValue As FirstWeekOfYear ) As Integer
Returns an Integer value containing the specified component of a given
Date value.
5
Public Shared Function Day (DateValue As DateTime) As Integer
Returns an Integer value from 1 through 31 representing the day of the
month.
6
Public Shared Function Hour (TimeValue As DateTime) As Integer
Returns an Integer value from 0 through 23 representing the hour of the
day.
7
Public Shared Function Minute (TimeValue As DateTime) As Integer
Returns an Integer value from 0 through 59 representing the minute of the
hour.
8
Public Shared Function Month (DateValue As DateTime) As Integer
Returns an Integer value from 1 through 12 representing the month of the
year.
9
Public Shared Function MonthName (Month As Integer, Abbreviate As
Boolean) As String
Returns a String value containing the name of the specified month.
10
Public Shared Function Second (TimeValue As DateTime) As Integer
Returns an Integer value from 0 through 59 representing the second of the
minute.
11
Public Overridable Function ToString As String
Returns a string that represents the current object.
12
Public Shared Function Weekday (DateValue As DateTime, DayOfWeek
As FirstDayOfWeek) As Integer
Returns an Integer value containing a number representing the day of the
week.
13
Public Shared Function WeekdayName (Weekday As Integer,
Abbreviate As Boolean, FirstDayOfWeekValue As FirstDayOfWeek) As
String
Returns a String value containing the name of the specified weekday.
14
Public Shared Function Year (DateValue As DateTime) As Integer
Returns an Integer value from 1 through 9999 representing the year.
The above list is not exhaustive. For complete list of properties and methods of the DateAndTime
class, please consult Microsoft Documentation.
The following program demonstrates some of these and methods −
Live Demo
Module Module1
Sub Main()
Dim birthday As Date
Dim bday As Integer
Dim month As Integer
Dim monthname As String
' Assign a date using standard short format.
birthday = #7/27/1998#
bday = [Link](birthday)
month = [Link](birthday)
monthname = [Link](month)
[Link](birthday)
[Link](bday)
[Link](month)
[Link](monthname)
[Link]()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
7/27/1998 12:00:00 AM
27
7
July
[Link] - Arrays
An array stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.
Eg;
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
[Link]("Element({0}) = {1}", j, n(j))
Next j
[Link]()
End Sub
End Module
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par
the need of the program. You can declare a dynamic array using
the ReDim statement.
Where,
The Preserve keyword helps to preserve the data in an existing array, when
you resize it.
arrayname is the name of the array to re-dimension.
subscripts specifies the new dimension.
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
For i = 0 To 10
[Link](i & vbTab & marks(i))
Next i
[Link]()
End Sub
End Module
O/p:-
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
Multi-Dimensional Arrays
[Link] allows multidimensional arrays. Multidimensional arrays are also called
rectangular arrays.
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4,
8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
[Link]("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
[Link]()
End Sub
End Module
O/p:-
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a
jagged array named scores of Integers −
For i = 0 To 4
For j = 0 To 1
[Link]("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
[Link]()
End Sub
End Module
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
The following table provides some of the most commonly used properties of
the Array class −
1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.
2 IsReadOnly
Gets a value indicating whether the Array is read-only.
Length
3
Gets a 32-bit integer that represents the total number of elements in all
the dimensions of the Array.
LongLength
4
Gets a 64-bit integer that represents the total number of elements in all
the dimensions of the Array.
5 Rank
Gets the rank (number of dimensions) of the Array.