0% found this document useful (0 votes)
23 views39 pages

Section B .Net Technology (1)

Visual Basic .NET (VB.NET) is an object-oriented programming language that is part of the .NET Framework, offering modern programming features and support for various data types. It allows for the creation of efficient programs across multiple platforms and includes features such as automatic garbage collection, properties, events, and easy-to-use generics. The document also covers basic syntax, variable declaration, constants, enumerations, and statements in VB.NET.

Uploaded by

killercoc302004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views39 pages

Section B .Net Technology (1)

Visual Basic .NET (VB.NET) is an object-oriented programming language that is part of the .NET Framework, offering modern programming features and support for various data types. It allows for the creation of efficient programs across multiple platforms and includes features such as automatic garbage collection, properties, events, and easy-to-use generics. The document also covers basic syntax, variable declaration, constants, enumerations, and statements in VB.NET.

Uploaded by

killercoc302004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

SECTION-B

VB.Net - Overview

Visual Basic .NET (VB.NET) is an object-oriented computer programming language


implemented on the .NET Framework. Although it is an evolution of classic Visual Basic
language, it is not backwards-compatible with VB6, and any code written in the old version
does not compile under VB.NET.

Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long,
String, Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherits
from the base class Object.
VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access to all
the libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the
open-source alternative to .NET, not only under Windows, but even Linux or Mac OSX.
The following reasons make VB.Net a widely used professional language −
• Modern, general purpose.
• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.

Strong Programming Features VB.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 - Basic Syntax

VB.Net is an object-oriented programming language. In Object-Oriented Programming


methodology, a program consists of various objects that interact with each other by means of
actions. The actions that an object may take are called methods. Objects of the same kind are
said to have the same type or, more often, are said to be in the same class.
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 instance 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.
• Class − A class can be defined as a template/blueprint that describes the
behaviors/states that objects of its type support.
• Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
• Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.

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.

VB.Net - Variables

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 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 VB.Net can
be categorized as −

Type Example

Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char

Floating point types Single and Double

Decimal types Decimal

Boolean types True or False values, as assigned

Date types Date

VB.Net 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.

Variable Declaration in VB.Net


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.
Syntax for variable declaration in VB.Net is −
[ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist
Where,
• attributelist is a list of attributes that apply to the variable. Optional.
• accessmodifier defines the access levels of the variables, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
• Shared declares a shared variable, which is not associated with any specific instance
of a class or structure, rather available to all the instances of the class or structure.
Optional.
• Shadows indicate that the variable re-declares and hides an identically named element,
or set of overloaded elements, in a base class. Optional.
• Static indicates that the variable will retain its value, even when the after termination
of the procedure in which it is declared. Optional.
• ReadOnly means the variable can be read, but not written. Optional.
• WithEvents specifies that the variable is used to respond to events raised by the
instance assigned to the variable. Optional.
• Variablelist provides the list of variables declared.
Each variable in the variable list has the following syntax and parts −
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
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.
Some valid variable declarations along with their definition are shown here −
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net


Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is −
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
You can initialize a variable at the time of declaration as follows −
Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"

Accepting Values from User


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,
Dim message As String
message = Console.ReadLine
The following example demonstrates it −
Live Demo
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
When the above code is compiled and executed, it produces the following result (assume the
user inputs Hello World) −
Enter message: Hello World
Your Message: Hello World

Lvalues and Rvalues


There are two kinds of expressions −
• lvalue − An expression that is an lvalue may appear as either the left-hand or right-
hand side of an assignment.
• rvalue − An expression that is an rvalue may appear on the right- but not left-hand side
of an assignment.
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 −
20 = g

VB.Net - Constants and Enumerations

Advertisements

Previous Page

Next Page
The constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified
after their definition.
An enumeration is a set of named integer constants.

Declaring Constants
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 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 −
Live Demo
Module constantsNenum
Sub Main()
Const PI = 3.14149
Dim radius, area As Single
radius = 7
area = PI * radius * radius
Console.WriteLine("Area = " & Str(area))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Area = 153.933

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 −
Live Demo
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
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

VB.Net - Statements

Advertisements

Previous Page

Next Page
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 VB.Net −

Sr.No Statements and Description Example

1 Dim number As
Dim Statement
Integer
Declares and allocates storage space for one or more variables. Dim quantity As
Integer = 100
Dim message As
String = "Hello!"

2 Const maximum As
Const Statement
Long = 1000
Declares and defines one or more constants. Const
naturalLogBase As
Object
=
CDec(2.7182818284

3 Enum
Enum Statement
CoffeeMugSize
Declares an enumeration and defines the values of its members. Jumbo
ExtraLarge
Large
Medium
Small
End Enum
4 Class Box
Class Statement
Public length As
Declares the name of a class and introduces the definition of the variables, Double
properties, events, and procedures that the class comprises. Public breadth As
Double
Public height As
Double
End Class

5 Structure Box
Structure Statement
Public length As
Declares the name of a structure and introduces the definition of the variables, Double
properties, events, and procedures that the structure comprises. Public breadth As
Double
Public height As
Double
End Structure

6 Public Module
Module Statement
myModule
Declares the name of a module and introduces the definition of the variables, Sub Main()
properties, events, and procedures that the module comprises. Dim user As String
InputBox("What is
your name?")
MsgBox("User nam
is" & user)
End Sub
End Module

7 Public Interface
Interface Statement
MyInterface
Declares the name of an interface and introduces the definitions of the Sub doSomething(
members that the interface comprises. End Interface

8 Function myFunctio
Function Statement
(ByVal n As Integer
Declares the name, parameters, and code that define a Function procedure. As Double
Return 5.87 * n
End Function

9 Sub mySub(ByVal s
Sub Statement
As String)
Declares the name, parameters, and code that define a Sub procedure. Return
End Sub

10 Declare Function
Declare Statement
getUserName
Declares a reference to a procedure implemented in an external file. Lib "advapi32.dll"
Alias
"GetUserNameA"
(
ByVal lpBuffer A
String,
ByRef nSize As
Integer) As Integer

11 Public Shared
Operator Statement
Operator +
Declares the operator symbol, operands, and code that define an operator (ByVal x As obj,
procedure on a class or structure. ByVal y As obj) As
obj
Dim r As New obj
' implemention code
for r = x + y
Return r
End Operator

12 ReadOnly Property
Property Statement
quote() As String
Declares the name of a property, and the property procedures used to store Get
and retrieve the value of the property. Return
quoteString
End Get
End Property

13 Public Event
Event Statement
Finished()
Declares a user-defined event.

14 Delegate Function
Delegate Statement
MathOperator(
Used to declare a delegate. ByVal x As
Double,
ByVal y As Doub
) As Double

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.
Example
The following example demonstrates a decision making statement −
Live Demo
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10

' check the boolean condition using if statement '


If (a < 20) Then
' if condition is true then print the following '
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
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 - Operators

Advertisements

Previous Page

Next Page

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. VB.Net 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 VB.Net. Assume
variable A holds 2 and variable B holds 7, then −
Show Examples

Operator Description Example

^ Raises one operand to the power of another B^A will give 49

+ Adds two operands A + B will give 9

- Subtracts second operand from the first A - B will give -5

* Multiplies both operands A * B will give 14

/ Divides one operand by another and returns a floating point result B / A will give 3.5

\ 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 VB.Net. Assume
variable A holds 10 and variable B holds 20, then −
Show Examples

Operator Description Exampl

= Checks if the values of two operands are equal or not; if yes, then condition becomes (A = B)
true. is not
true.

<> Checks if the values of two operands are equal or not; if values are not equal, then (A <> B
condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right operand; if yes, (A > B)
then condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right operand; if yes, then (A < B)
condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the value of right (A >= B
operand; if yes, then condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of right operand; (A <= B
if yes, then condition becomes true. is true.

Apart from the above, VB.Net 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 VB.Net. Assume variable A
holds Boolean value True and variable B holds Boolean value False, then −
Show Examples

Operator Description Exampl

And It is the logical as well as bitwise AND operator. If both the operands are true, then (A And
condition becomes true. This operator does not perform short-circuiting, i.e., it B) is
evaluates both the expressions. False.
Or It is the logical as well as bitwise OR operator. If any of the two operands is true, (A Or B
then condition becomes true. This operator does not perform short-circuiting, i.e., it is True.
evaluates both the expressions.

Not It is the logical as well as bitwise NOT operator. Use to reverses the logical state of Not(A
its operand. If a condition is true, then Logical NOT operator will make false. And B)
is True.

Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns True if A Xor B
both expressions are True or both expressions are False; otherwise it returns False. is True.
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 short- (A
circuiting. AndAls
B) is
False.

OrElse It is the logical OR operator. It works only on Boolean data. It performs short- (A
circuiting. OrElse
B) is
True.

IsFalse It determines whether an expression is False.

IsTrue It determines whether an expression is True.

Bit Shift Operators


We have already discussed the bitwise operators. The bit shift operators perform the shift
operations on binary values. Before coming into the bit shift operators, let us understand the
bit operations.
Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and
^ are as follows −

p q p&q p|q p^q

0 0 0 0 0
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 VB.Net 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 −
Show Examples

Operator Description Example

And Bitwise AND Operator copies a bit to the result if it exists in both operands. (A AND B
will give
12, which i
0000 1100

Or Binary OR Operator copies a bit if it exists in either operand. (A Or B)


will give
61, which i
0011 1101

Xor Binary XOR Operator copies the bit if it is set in one operand but not both. (A Xor B)
will give
49, which i
0011 0001
Not Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (Not A )
will give -
61, which i
1100 0011
in 2's
complemen
form due to
a signed
binary
number.

<< Binary Left Shift Operator. The left operands value is moved left by the number A << 2 wil
of bits specified by the right operand. give 240,
which is
1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the A >> 2 wil
number of bits specified by the right operand. give 15,
which is
0000 1111

Assignment Operators
There are following assignment operators supported by VB.Net −
Show Examples

Operator Description Exampl

= Simple assignment operator, Assigns values from right side operands to left side C=A+
operand B will
assign
value of
A+B
into C

+= Add AND assignment operator, It adds right operand to the left operand and C += A i
assigns the result to left operand equivalen
to C = C
+A
-= Subtract AND assignment operator, It subtracts right operand from the left operand C -= A is
and assigns the result to left operand equivalen
to C = C
A

*= Multiply AND assignment operator, It multiplies right operand with the left C *= A i
operand and assigns the result to left operand equivalen
to C = C
*A

/= Divide AND assignment operator, It divides left operand with the right operand and C /= A is
assigns the result to left operand (floating point division) equivalen
to C = C
A

\= Divide AND assignment operator, It divides left operand with the right operand and C \= A is
assigns the result to left operand (Integer division) equivalen
to C = C
\A

^= Exponentiation and assignment operator. It raises the left operand to the power of C^=A is
the right operand and assigns the result to left operand. equivalen
to C = C
A

<<= Left shift AND assignment operator C <<= 2


is same a
C = C <<
2

>>= Right shift AND assignment operator C >>= 2


is same a
C = C >>
2

&= Concatenates a String expression to a String variable or property and assigns the Str1 &=
result to the variable or property. Str2 i
same as
Str1 =
Str1 &
Str2
Miscellaneous Operators
There are few other important operators supported by VB.Net.
Show Examples

Operator Description Example

AddressOf Returns the address of a procedure. AddHandler Button1.Click,


AddressOf Button1_Click

Await It is applied to an operand in an asynchronous


method or lambda expression to suspend execution Dim result As res
of the method until the awaited task completes. = Await
AsyncMethodThatReturnsResult()
Await AsyncMethod()

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
Console.WriteLine(add5(5))

If It uses short-circuit evaluation to conditionally Dim num = 5


return one of two values. The If operator can be Console.WriteLine(If(num >= 0,
called with three arguments or with two arguments. "Positive", "Negative"))

Operators Precedence in VB.Net


Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated
first.
Show Examples

Operator Precedence
Await Highest

Exponentiation (^)

Unary identity and negation (+, -)

Multiplication and floating-point division (*, /)

Integer division (\)

Modulus arithmetic (Mod)

Addition and subtraction (+, -)

Arithmetic bit shift (<<, >>)

All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)

Negation (Not)

Conjunction (And, AndAlso)

Inclusive disjunction (Or, OrElse)

Exclusive disjunction (Xor) Lowest

VB.Net - Loops

Advertisements

Previous Page
Next Page

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 provides following types of loops to handle looping requirements. Click the following
links to check their details.

Loop Type Description

Do Loop It repeats the enclosed block of statements while a Boolean condition is Tru
or until the condition becomes True. It could be terminated at any time wit
the Exit Do statement.

For...Next 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.

It repeats a group of statements for each element in a collection. This loop is used fo
For Each...Next
accessing and manipulating all elements in an array or a VB.Net collection.
While... End While It executes a series of statements as long as a given condition is True.

With... End With It is not exactly a looping construct. It executes a series of statements tha
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.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.
VB.Net provides the following control statements. Click the following links to check their
details.

Control Statement Description

Exit statement Terminates the loop or select case statement and transfers
execution to the statement immediately following the loop or
select case.

Continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

GoTo statement Transfers control to the labeled statement. Though it is not advised
to use GoTo statement in your program.

VB.Net - Arrays

Advertisements

Previous Page

Next Page
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.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

Creating Arrays in VB.Net


To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index of the array. The
following program demonstrates this −
Live Demo
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
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
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.
Syntax for ReDim statement −
ReDim [Preserve] arrayname(subscripts)
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

ReDim Preserve marks(10)


marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75

For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
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

Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular
arrays.
You can declare a 2-dimensional array of strings as −
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables −
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array −
Live Demo
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

Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a jagged array
named scores of Integers −
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array −
Live Demo
Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {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

VB.Net - Collections

Advertisements
Previous Page

Next Page

Collection classes are specialized classes for data storage and retrieval. These classes provide
support for stacks, queues, lists, and hash tables. Most collection classes implement the same
interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements
and accessing a list of items on the basis of an index, etc. These classes create collections of
objects of the Object class, which is the base class for all data types in VB.Net.

Various Collection Classes and Their Usage


The following are the various commonly used classes of the System.Collection namespace.
Click the following links to check their details.

Class Description and Useage

ArrayList It represents ordered collection of an object that can be indexed individually.


It is basically an alternative to an array. However, unlike array, you can add and
remove items from a list at a specified position using an index and the array
resizes itself automatically. It also allows dynamic memory allocation, add,
search and sort items in the list.

Hashtable It uses a key to access the elements in the collection.


A hash table is used when you need to access elements by using key, and you
can identify a useful key value. Each item in the hash table has a key/value pair.
The key is used to access the items in the collection.

SortedList It uses a key as well as an index to access the items in a list.


A sorted list is a combination of an array and a hash table. It contains a list of
items that can be accessed using a key or an index. If you access items using an
index, it is an ArrayList, and if you access items using a key, it is a Hashtable.
The collection of items is always sorted by the key value.

Stack It represents a last-in, first out collection of object.


It is used when you need a last-in, first-out access of items. When you add an
item in the list, it is called pushing the item, and when you remove it, it is
called popping the item.
Queue It represents a first-in, first out collection of object.
It is used when you need a first-in, first-out access of items. When you add an
item in the list, it is called enqueue, and when you remove an item, it is
called deque.

BitArray It represents an array of the binary representation using the values 1 and 0.
It is used when you need to store the bits but do not know the number of bits in
advance. You can access items from the BitArray collection by using an integer
index, which starts from zero.

VB.Net - Functions

Advertisements

Previous Page

Next Page

A procedure is a group of statements that together perform a task when called. After the
procedure is executed, the control returns to the statement calling the procedure. VB.Net has
two types of procedures −
• Functions
• Sub procedures or Subs
Functions return a value, whereas Subs do not return a value.

Defining a Function
The Function statement is used to declare the name, parameter and the body of a function. The
syntax for the Function statement is −
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
• Modifiers − specify the access level of the function; possible values are: Public,
Private, Protected, Friend, Protected Friend and information regarding overloading,
overriding, sharing, and shadowing.
• FunctionName − indicates the name of the function
• ParameterList − specifies the list of the parameters
• ReturnType − specifies the data type of the variable the function returns

Example
Following code snippet shows a function FindMax that takes two integer values and returns
the larger of the two.
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function

Function Returning a Value


In VB.Net, a function can return a value to the calling code in two ways −
• By using the return statement
• By assigning the value to the function name
The following example demonstrates using the FindMax function −
Live Demo
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer

res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Max value is : 200

Recursive Function
A function can call itself. This is known as recursion. Following is an example that calculates
factorial for a given number using a recursive function −
Live Demo
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Param Arrays
At times, while declaring a function or sub procedure, you are not sure of the number of
arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into help
at these times.
The following example demonstrates this −
Live Demo
Module myparamfunc
Function AddElements(ParamArray arr As Integer()) As Integer
Dim sum As Integer = 0
Dim i As Integer = 0

For Each i In arr


sum += i
Next i
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = AddElements(512, 720, 250, 567, 889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
The sum is: 2938

Passing Arrays as Function Arguments


You can pass an array as a function argument in VB.Net. The following example demonstrates
this −
Live Demo
Module arrayParameter
Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0

For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with 5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
avg = getAverage(balance, 5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Average value is: 214.4
Defining Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a sub procedure.
The syntax for the Sub statement is −
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
• Modifiers − specify the access level of the procedure; possible values are - Public,
Private, Protected, Friend, Protected Friend and information regarding overloading,
overriding, sharing, and shadowing.
• SubName − indicates the name of the Sub
• ParameterList − specifies the list of the parameters

Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee −
Live Demo
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00

Passing Parameters by Value


This is the default mechanism for passing parameters to a method. In this mechanism, when
a method is called, a new storage location is created for each value parameter. The values of
the actual parameters are copied into them. So, the changes made to the parameter inside the
method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword. The following
example demonstrates the concept −
Live Demo
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside the function.

Passing Parameters by Reference


A reference parameter is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage location is not created for
these parameters. The reference parameters represent the same memory location as the actual
parameters that are supplied to the method.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following
example demonstrates this −
Live Demo
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

VB.Net - Classes & Objects

Advertisements

Previous Page

Next Page

When you define a class, you define a blueprint for a data type. This doesn't actually define
any data, but it does define what the class name means, that is, what an object of the class will
consist of and what operations can be performed on such an object.
Objects are instances of a class. The methods and variables that constitute a class are called
members of the class.

Class Definition
A class definition starts with the keyword Class followed by the class name; and the class
body, ended by the End Class statement. Following is the general form of a class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
• attributelist is a list of attributes that apply to the class. Optional.
• accessmodifier defines the access levels of the class, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
• Shadows indicate that the variable re-declares and hides an identically named element,
or set of overloaded elements, in a base class. Optional.
• MustInherit specifies that the class can be used only as a base class and that you cannot
create an object directly from it, i.e., an abstract class. Optional.
• NotInheritable specifies that the class cannot be used as a base class.
• Partial indicates a partial definition of the class.
• Inherits specifies the base class it is inheriting from.

Comparison Table Between Namespace and Assembly


Parameters of
Namespace Assembly
Comparison

An assembly has two categories, namely,


No further classifications are made in private and public. The former is specific
Classification
namespace. to one application while the latter can be
used in multiple applications.

Assembly forms the logical unit of


A namespace is a feature in coding
functionality as it contains a huge
Grouping languages like C++ and C# where it
collection of types and resources working
forms the basis of logical code grouping.
together.

It is a feature used to declare a scope and Used in .NET-based applications for


Application
organize code into a logical group. deployment, version control, etc.

Various applications are allowed to share


Global scope It is declared at a global scope. assemblies among them by putting them
in the global assembly cache (GAC).

A namespace is a feature whose


Nesting declaration can be nested with another Nesting is not allowed in assemblies.
namespace.

In C++, a namespace can be defined by In assembly, the executable files


Naming
using the keyword “namespace” followed generally end with .exe or .dll extensions.
by assigning a name to it. For example,
namespace ns1

What is Namespace?

A namespace is best defined as a declarative region that can provide scope to the identifiers
inside it. It is a feature that helps to group and organize code in a logical way that clears the
confusion by eradicating the chances of overlapping.
In the case of using multiple libraries, overlapping of names is a very common inconvenience
that coders deal with regularly. But, one of the best perks of using a namespace is that it
prevents the collision of names.
There are several identifiers in the namespace scope and all of them are visible to one another
without any qualification. Identifiers that are present outside the namespace can also have
access to the members, either by using the fully qualified name of an identifier or using a
declaration for a single identifier.

To declare a namespace, using the keyword “namespace” followed by a space then the
variable name is the proper syntax. It doesn’t need a semicolon at the end of the line or
declaration.
An identifier is declared in an explicit namespace apart from the entry point main function
which is declared in the global namespace.

What is Assembly?

Assemblies are best defined as the fundamental unit of logical code grouping. This means
executing purposes like deployment, security permissions, reuse, etc. for the .NET-based
applications, assemblies are very important.
ADVERTISING
An assembly, in simple words, represents a collection of types and resources that are built
together either in an executable form (.exe) or a dynamic link (.dll). To know the type
implementations, the assembly also provides specific information with common language
runtime.

In the case of .NET Core and .NET Framework, the user has the advantage to access more
than one source code files to develop an assembly. An assembly can also contain more than
one module in the case of .NET Framework. Due to these flexibilities, it helps the developers
work on different source code files and then put them together for an assembly. This is what
generally happens when working on a large project.

Assemblies are also loaded into the memory as per requirement. Since it is optionable to load
the assemblies, the resource management becomes more efficient and smarter.
Assemblies can be both static and dynamic types. In static assemblies, they are stored in the
disk in portable executable files whereas dynamic assemblies don’t require saving before
execution. They can run directly from the memory.

Types of Assemblies of in .NET Framework:


In the .NET Framework, there are two types of assemblies. They are as follows:
1. EXE (Executable)
2. DLL (Dynamic Link Library)
In .NET Framework when we compile a Console Application or a Windows Application, it
generates EXE, whereas when we compile a Class Library Project or ASP.NET web application,
then it generates DLL. In.NET framework, both EXE, and DLL are called assemblies.

What is the difference between an EXE and a DLL and how is it


getting generated?

dll - dynamic link library


If an assembly is compiled as a class library and provides types for other assemblies to use,
then it has the file extension .dll (dynamic link library),
DLL cannot be executed standalone.
DLL cannot be directly executed as they're designed to be loaded and run by other programs
DLL would share the same process and memory space of the calling application
They can be reused for some other application. As long as the coder knows the names and
parameters of the functions and procedures in the DLL file .
EXE - executable file format
If an assembly is compiled as an application, then it has the file extension .exe
EXE can be executed standalone.
EXE creates its separate process and memory space.

Comparison Table Between EXE and DLL


Parameter of
EXE DLL
Comparison

Full-Form It stands for executable files. It stands for Dynamic Link Library.

Exe files are independent. They can


These are generally used as a supportive file,
Run-time execute without support of other
in order to run other applications.
applications.
When talking about a single application
DLL file numbers are not fixed. There might
Numbers package, only one executable file is
be one or more DLL files.
present.

Does not require any extra memory space.


The extension requires more storage and
Memory Uses the memory space of the application
memory.
that it is running.

Cannot be shared with other application. Can be shared with other applications. They
Sharing
Thus, they are not reusable. are reusable.

Type An exe is a program. DLL is a library.

What is an EXE?

On Windows, the programs to-be compiled have an .exe extension are referred
as ‘EXE files.’

The term EXE stands for an executable file. Its main function is to run a
program when it is opened. This is done by the execution of certain codes or
some of the information that is contained in the file.

Whenever a program or app is run on the Windows PC, it is actually the .exe
file that makes it able to run the programs or apps. But one more thing with the
extension is that it may be used to spread malware and other viruses.

Users need to be alert when they receive a .exe file from unknown sources.
There is a maximum probability that it might contain malware.

Basically, there are two types of executable files. The compilation of both the
files has been done from the source codes. The codes are converted into binary
code and the execution is done by the CPU.

1. Compiled program- On Windows, compiled programs are the ones


that have a .exe file extension.
2. Scripts- Executable files that are uncompiled are referred to as
scripts. These files are saved in the form of plain text format.
Scripts usually do not have executable machine codes in which
case they require an interpreter to run the program.
What is DLL?
Dynamic Library Link or dll is a file type that consists of certain instructions
that other programs make use of when in need. It is a library of various
information and function that are accessible by a Windows program.

DLL files are not capable of running directly. Instead, they need to be called
upon by some other code that is running on the computer.

‘Dynamic’ word is used in a dynamic link. This means that the data is used in
programs when the program calls for it. The data is not available in the memory
permanently. A DLL file consists of a .dll extension.

These are basically made up of C++ programming language. So, anyone with
the knowledge of coding may easily write their own DLL code.

A large number of DLL files are available on Windows by default. But they can
also be installed by third-party programs. DLL files, allow us to separate
different components from a program into a different module.

DLL provides one with a unique feature. There can be an update of the program
without having to reinstall the entire program all again.

You might also like