Visual Basic DotNet
Visual Basic DotNet
NET
o Object oriented.
o Component oriented.
o Easy to learn.
o Structured language.
ProgrammingFeaturesVB.Net
VB.Net has numerous strong programming features that make it endearing to multitude of programmers
worldwide. Let us mention some of these features:
▪ Boolean Conditions
▪ Automatic Garbage Collection
▪ Standard Library
▪ Assembly Versioning
▪ Properties and Events
▪ Delegates and Events Management
▪ Easy-to-use Generics
▪ Indexers
▪ Conditional Compilation
▪ Simple Multithreading
VB.NET
The last two are free. Using these tools, you can write all kinds of VB.Net programsfrom simple
command-line applications to more complex applications. Visual BasicExpress and Visual Web
Developer Express edition are trimmed down versions ofVisual Studio and has the same look
and feel.
Program Structure:
A VB.Net program basically consists of the following parts:
➢ Namespace declaration
➢ A class or module
➢ Variables
➢ Comments
Let us look at a simple code that would print the words "Hello World":
Imports System
Module Module1
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
VB.NET
The first line of the program Imports System is used to include the Systemnamespace in
the program.
The next line has a Module declaration, the module Module1. VB.Net is completely
object oriented, so every program must contain a module of a class that contains the data
and procedures that your program uses.
Classes or Modules generally would contain more than one procedure. Procedures
contain the executable code, or in other words, they define thebehavior of the class. A
procedure could be any of the following:
▪ Function
▪ Sub
▪ Operator
▪ Get
▪ Set
▪ AddHandler
▪ RemoveHandler
▪ RaiseEvent
The next line ('This program) will be ignored by the compiler and it has been put to add
additional comments in the program.
The next line defines the Main procedure, which is the entry point for all VB.Net
programs. The Main procedure states what the module or class willdo when executed.
WriteLine is a method of the Console class defined in the System namespace. This
statement causesthe message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey() is for the VS.NET Users. This will preventthe screen
from running and closing quickly when the program is launchedfrom Visual Studio .NET.
VB.NET
Click the Run button or the F5 key to run the project. A Command Promptwindow appears that
contains the line Hello World.
You can compile a VB.Net program by using the command line instead of the VisualStudio IDE:
When we consider a VB.Net program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods,
and instant variables mean.
• Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of
a class.
VB.NET
• Instant Variables - Each object has its unique set of instant variables. An object's state
is created by the values assigned to these instant variables.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on
the basis of our observations in it:
VB.NET
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
End Sub
Public Function GetArea() As Double
GetArea = length * width
End Function
Public Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
Shared Sub Main()
Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
End Class
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 3.5
Area: 15.75
we created a Visual Basic module that held the code. Sub Main indicates the entry point of VB.Net
program. Here, we are using Class that contains both code and data. You use classes to create
objects. For example, in the code, r is a Rectangle object.
VB.NET
A class may have members that can be accessible from outside class, if so specified. Data members
are called fields and procedure members are called methods.
Shared methods or static methods can be invoked without creating an object of the class. Instance
methods are invoked through an object of the class:
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 VB.Net 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.
GetXML
Friend Function Get GetType Global GoTo
Namespace
Handles If Implem Imports In Inherits Integer
ents
Not Not
Object Of On Operator Option
Inheritable Overridable
Optional Or OrElse Overloads Overridabl Overrides ParamArr
e ay
Remove
ReDim REM Resume Return SByte Select
Handler
Set Shadows Shared Short Single Static Step
Data types:
Data types refer to an extensive system used for declaring variables or functions of different types.
The type of a variable determines how much space it occupies in storage and how the bit pattern
stored is interpreted
Storage
Data Type Value Range
Allocation
Depends on
Boolean implementing True or False
platform
0 through +/-
79,228,162,514,264,337,593,543,950,335
(+/-7.9...E+28) with no decimal point; 0
Decimal 16 bytes
through +/-
7.9228162514264337593543950335 with
28 places to the right of the decimal
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative
values
Double 8 bytes
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive
values
VB.NET
-9,223,372,036,854,775,808 through
Long 8 bytes
9,223,372,036,854,775,807(signed)
4 bytes on 32-bit
platform Any type can be stored in a variable of type
Object
8 bytes on 64-bit Object
platform
Depends on
0 to approximately 2 billion Unicode
String implementing
characters
platform
0 through 18,446,744,073,709,551,615
ULong 8 bytes
(unsigned)
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)
13 CStr(expression)
16 CUShort(expression)
Variable
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in VB.Net has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored withinthat memory; and the set of operations that
can be applied to the variable
Type Example
Variable Declarations:
The Dim statement is used for variable declaration and storage allocation for one or more
variables. The Dim statement is used at module, class, structure, procedure, or block level.
VB.NET
Where,
Each variable in the variable list has the following syntax and parts:
Where,
➢ variablename: is the name of the variable
➢ boundslist: optional. It provides list of bounds of each dimension of an array variable.
➢ New: optional. It creates a new instance of the class when the Dim statement runs.
➢ datatype: Required if Option Strict is On. It specifies the data type of the variable.
➢ initializer: Optional if New is not specified. Expression that is evaluated and assigned
to the variable when it is created.
VB.NET
Some valid variable declarations along with their definition are shown here:
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c = a + b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module
AcceptingValuesfromUser:
The Console class in the System namespace provides a function ReadLine for accepting
input from the user and store it into a variable. For example,
Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
VB.NET
When the above code is compiled and executed, it produces the following result
(assume the user inputs Hello World):
Lvalues andRvalues
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals
are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a
valid statement:
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time error:
Dim g As Integer = 20
In VB.Net, constants are declared using the Const statement. The Const statement is used at
module, class, structure, procedure, or block level for use inplace of literal values.
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:
For example,
Enumerations:
An enumerated type is declared using the Enum statement. The Enum statement declares an
VB.NET
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.
• asscessmodifier: 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
Example:
Module constantsNenum
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Sub Main()
Console.WriteLine("The Color Red is : " & Colors.red)
Console.WriteLine("The Color Yellow is : " & Colors.yellow)
Console.WriteLine("The Color Blue is : " & Colors.blue)
Console.WriteLine("The Color Green is : " & Colors.green)
Console.ReadKey()
End Sub
End Module
VB.NET
Constant Description
vbNullString Not the same as a zero-length string (""); used for callingexternal
procedures.
vbObjectError Error number. User-defined error numbers should be greater than this
value. For example: Err.Raise(Number) = vbObjectError + 1000
Statement
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
VB.NET
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.
1 Dim Statement
Dim number As
Declares and allocates storage space for one Integer
or more variables. Dim quantity As
Integer = 100
Dim message As
String = "Hello!"
2 Const Statement
Const maximum As
Declares and defines one or more constants.
Long = 1000
Const naturalLogBaseAs
Object
= CDec(2.7182818284)
VB.NET
3 Enum Statement
Enum CoffeeMugSize
Declares an enumeration and defines thevalues
Jumbo
of its members.
ExtraLarge Large
Mediu
m
Small
End Enum
4 Class Statement
Class Box
Declares the name of a class and introducesthe
Public length As
definition of the variables, properties,
Double
events, and procedures that the class
Public breadth As
comprises.
Double
Public height As
Double
End Class
5 Structure Statement
Structure Box
Declares the name of a structure and
Public length As
introduces the definition of the variables,
Double
properties, events, and procedures that the
Public breadth As
structure comprises.
Double
Public height As
Double
End Structure
6 Module Statement
Declares the name of a module and introduces the Public Module myModule
definition of the variables, properties, events, and
Sub Main()
VB.NET
Public Interface
Declares the name of an interface and introduces the MyInterface
definitions of the members that the interface comprises.
Sub doSomething()
End Interface
8 Function Statement
Declares the name, parameters, and code that define a Function myFunction
Function procedure.
(ByVal n As Integer) As
Double
Return 5.87 * n End
Function
9 Sub Statement
Declares the name, parameters, and code that define a Sub mySub(ByVal s As
Sub procedure. String)
Return End Sub
10 Declare Statement
Declares a reference to a procedure implemented in an Declare Function
external file. getUserName
Lib "advapi32.dll" Alias
"GetUserNameA" (
ByVal lpBuffer As String,
ByRef nSize As Integer) As
Integer
11 Operator Statement
Declares the operator symbol, operands, and code that
VB.NET
Executable Statement
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
Statement Description
nested Select Case statements You can use one select case statementinside
another select case statement(s).
If condition Then
[Statement(s)]
End If
If the condition evaluates to true, then the block of code inside the If statement will be executed.
If condition evaluates to false, then the first set of code after the end of the If statement (after the
closing End If) will be executed.
Flow Diagram
Example:
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 10
When the above code is compiled and executed, it produces the following result:
a is less than 20
value of a is : 10
VB.NET
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
VB.NET
Example
Module decisions
Sub Main()
Dim a As Integer = 100
When the above code is compiled and executed, it produces the following result:
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
When using If... Else If... Else statements, there are few points to keep in mind.
1. An If can have zero or one Else's and it must come after an Else If's.
2. An If can have zero to many Else If's and they must come before the Else.
3. Once an Else if succeeds, none of the remaining Else If's or Else's will be tested.
Example:
Module decisions
Sub Main()
Nested If Statements
It is always legal in VB.Net to nest If-Then-Else statements, which means you can use one If or
ElseIf statement inside another If ElseIf statement(s).
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
If (a = 100) Then
If (b = 200) Then
Console.WriteLine("Value of a is 100 and b is 200")
End If
End If
Console.WriteLine("Exact value of a is : {0}", a)
Console.WriteLine("Exact value of b is : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Syntax
The syntax for a Select Case statement in VB.Net is as follows:
Where,
• expression: is an expression that must evaluate to any of the elementary data type in
VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object,
SByte, Short, Single, String, UInteger, ULong, and UShort.
• 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.
VB.NET
Example
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well
done")Case "D"
Console.WriteLine("You
passed")Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}",
grade)Console.ReadLine()
End Sub
End Module
loop statement
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:
VB.NET
VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.
Nested loops You can use one or more loops inside any another
While, For or Do loop.
Do While
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.
Do While loop is used to execute blocks of statements in the program, as long as the condition
remains true. It is similar to the While End Loop, but there is slight difference between them. The
while loop initially checks the defined condition, if the condition becomes true, the while loop's
statement is executed. Whereas in the Do loop, is opposite of the while loop, it means that it
executes the Do statements, and then it checks the condition.
the Do keyword followed a block of statements, and While keyword checks Boolean_expression
after the execution of the first Do statement.
VB.NET
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 15
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
VB.NET
For ..Next
It repeats a group of statements a specified number of times and a loop indexcounts the number
of loop iterations as the loop executes. A For Next loop is used to repeatedly execute a sequence
of code or a block of code until a given condition is satisfied. A For loop is useful in such a case
when we know how many times a block of code has to be executed
Flow Diagram
Example
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 1 To 5
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
VB.NET
It repeats a group of statements for each element in a collection. This loop is usedfor accessing and
manipulating all elements in an array or a VB.Net collection
In the VB.NET, For Each loop is used to iterate block of statements in an array or collection
objects. Using For Each loop, we can easily work with collection objects such as lists, arrays, etc.,
to execute each element of an array or in a collection. And when iteration through each element
in the array or collection is complete, the control transferred to the next statement to end the loop.
Example
Module loops
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
'displaying the values
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
1
3
5
7
9
VB.NET
While.. End
It executes a series of statements as long as a given condition is True. The While End loop is used
to execute blocks of code or statements in a program, as long as the given condition is true. It is
useful when the number of executions of a block is not known. It is also known as an entry-
controlled loop statement, which means it initially checks all loop conditions. If the condition is
true, the body of the while loop is executed. This process of repeated execution of the body
continues until the condition is not false. And if the condition is false, control is transferred out of
the loop.
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is logical true. The loop iterates while the condition is true.When the condition
becomes false, program control passes to the line immediately following the loop.
Flow Diagram
VB.NET
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 = 1
' while loop execution '
While a < 5
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
1
2
3
4
5
With object
[
statements ]End
With
VB.NET
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 = "VB.Net Programming"
.Author = "SKS"
.Subject = "Information Technology"
End With
With aBook
Console.WriteLine(.Name)
Console.WriteLine(.Author)
Console.WriteLine(.Subject)
End With
Console.ReadLine()
End Sub
End Module
Continue statement Causes the loop to skip the remainder of its body
and immediately retest its condition prior to
reiterating.
Exit Statement
The Exit statement transfers the control from a procedure or block immediately to the statement
following the procedure call or the block definition. It terminates the loop, procedure, try block or
the select block from where it is called.If you are using nested loops (i.e., one loop inside another
loop), the Exit statement will stop the execution of the innermost loop and start executing the next
line of code after the block.
Syntax
The syntax for the Exit statement is:
Flow Diagram
VB.NET
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 1
' while loop execution '
While (a < 20)
Console.WriteLine("value of a: {0}", a)
a = a + 1
If (a < 5) Then
'terminate the loop using exit statement
Exit While
End If
End While
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Value of a is 1
Value of a is 2
Value of a is 3
Value of a is 4
Continue Statement
The Continue statement causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating. It works somewhat like the Exit statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the For...Next loop, Continue statement causes the conditional test and increment portions of
the loop to execute. For the While and Do...While loops, continue statement causes the program
control to pass to the conditional tests.
Syntax
The syntax for a Continue statement is as follows:
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 1
Do
If (a = 3) Then
' skip the iteration '
a = a + 1
Continue Do
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 5)
Console.ReadLine()
End Sub
End Module
VB.NET
When the above code is compiled and executed, it produces the following result:
Value of a is 1
Value of a is 2
Value of a is 4
GoTo Statement
The GoTo statement transfers control unconditionally to a specified line in a procedure.
The syntax for the GoTo statement is:
GoTo label
VB.NET
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
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
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
VB.NET
Array
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.
An array is a linear data structure that is a collection of data elements of the same type stored on
a contiguous memory location. Each data item is called an element of the array. It is a fixed size
of sequentially arranged elements in computer memory with the first element being at index 0 and
the last element at index n - 1, where n represents the total number of elements in the array.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
To declare an array in VB.Net, you use the Dim statement. For example,
You can also initialize the array elements while declaring the array. For example,
The elements in an array can be stored and accessed by using the index of the array. The following
program demonstrates this:
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
For j = 0 To 5
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Dynamic Ar ays
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.
Syntax for 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.
VB.NET
When the above code is compiled and executed, it produces the following result:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
Multidimensional Array
VB.Net allows multidimensional arrays. Multidimensional arrays are also calledrectangular
arrays.
You can declare a 2-dimensional array of strings as:
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
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
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 Array class is the base class for all the arrays in VB.Net. It is defined in the System
namespace. The Array class provides various properties and methods to work with arrays.
VB.NET
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.
3 Length
Gets a 32-bit integer that represents the total number of elements in all
the dimensions of the Array.
4 LongLength
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.
VB.NET
Methods of theArrayClass
Module arrayApl
Sub Main()
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim temp As Integer() = list
Dim i As Integer
Console.Write("Original Array: ")
For Each i In list
Console.Write("{0} ", i)
Next i
Console.WriteLine()
' reverse the array
Array.Reverse(temp)
Console.Write("Reversed Array: ")
For Each i In temp
Console.Write("{0} ", i)
Next i
Console.WriteLine()
'sort the array
Array.Sort(list)
Console.Write("Sorted Array: ")
For Each i In list
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72