0% found this document useful (0 votes)
14 views25 pages

Chap 2 and 3

This document provides an overview of fundamental concepts in VB.NET, including keywords, identifiers, data types, literals, and variables. It details reserved and unreserved keywords, the rules for naming identifiers, and the various data types available in VB.NET, such as numeric and non-numeric types. Additionally, it explains the significance of literals and variables in programming with VB.NET.

Uploaded by

Arshdeep Kaur
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)
14 views25 pages

Chap 2 and 3

This document provides an overview of fundamental concepts in VB.NET, including keywords, identifiers, data types, literals, and variables. It details reserved and unreserved keywords, the rules for naming identifiers, and the various data types available in VB.NET, such as numeric and non-numeric types. Additionally, it explains the significance of literals and variables in programming with VB.NET.

Uploaded by

Arshdeep Kaur
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/ 25

Finwamentals of~

Every language has its own rules to define basic elements like identifiers, constant
and data types. This chapter explains the basic concepts of variables, identifierss
keywords and operators from VB.NET perspective. The knowledge of these concept~
helps in writing programs according to the rules of VB.NET language and reduces the
chances of syntax errors .

DJ KEYWORDS
Keywords have a specific meaning in_ a __programming language. VB.NET also
supports two types of Keywords-Reserved Keywords and Unreserved Keywords.

2.1.1 Reserved Keywords


Reserved keywords should not be_ used__for_any_ other pw:pose like naming an
idehtifiei:. However, this restriction can be overlooked by enclosing reserved keywords
in square brackets. The reserved keywords used in VB.NET are listed in Table 2.1.
Table 2.1: Reserved Keywords

AddHandler AddressOf Alias And AndAlso As Boolean


ByRef Byte ByVal Call Case Catch CBool
CByte CChar CDate CDec CDbl Char Clnt
Class CLng CObj Const Continue CSByte CShort
CSng CStr CType CUlnt CULng CUShort Date
Decimal Declare Default Delegate Dim DirectCast Do
Double Each Else Elself End End If Enum
Erase Error Event Exit False Finally For
Friend Function Get GetType GetXML Global GoTo
Namespace
Handles If Implements Imports In Inherits Integer
Interface Is lsNot Let Lib Like Long
Loop Me Mod Module Mustlnherit MustOverride MyBase
MyClass Namespace Narrowing New Next Not Nothing
Not Inheritable Not Object Of On Operator Option
Overridable
Or OrElse Overloads Overridable Overrides ParamArra
y
Private Property Protected Public Raise Event ReadOnly
REM Remove Resume Return SByte Select
Handler
Shadows Shared Short Single Static Step
String Structure Sub SyncLock Then Throw
True Try TryCast TypeOf Ulnteger While
With WithEvents WriteOnly Xor #Const #Else

Funoomentafs of VB.NET flJ
#Elself #End #If = & I &= *

*== I /= \ \= I\
"=
+ += - -- » Operator »= Operator <<
<<==

Keywords like Endlf, GoSub, Variant and Wend are retained as reserved keywords,
although they are no longer used in Visual Basic. The meaning of the keyword, Let, has
been changed and it is used in LINQ queries.

2.1.2 Unreserved Keywords


Unreserved keywords can be used as identifiers, but this should be avoided for
better pro~amming practices. The unreserved keywords are listed in Table 2.2.

Table 2.2: Unreserved Keywords

Aggregate Ansi Assembly Async Aut9 &ait ..Binary


Compare Custom Distinct Equals Explicit From Group By
Group Join Into IsFalse ls1hie Iterator Join Key
Mid Off Order By Preserve Skip Skip While Strict
Take Take While Text Unicode Until Where Yield
# ExternalSource #Region

fZJ IDENTIFIERS
An identifier in VB...NET_is_a_user-defined name that can be used for a variable
name, function name, c~as~..nIDTie,_array name et~. Rules to name an identifi~ __in-
VB.NET are listed below.
An Identifier name should start with a letter (alphabet) followed by a sequence of
letters, digits (0 - 9) or underscore (_).
It must not contain any embedded space i.e. white spaces or SY!!!Q._ol ~e ?, -, +,!, @,
#, %, ", &, *, (, ), [,], {, }, ., ;, :, ", ',/,and\. These symbols are not allowed in assigning
a name to an identifier.
It should not be a..reserned key.word _oLVB.NET, This restriction can be bypassed by
enclosing the keyword in square brackets. But it is not a good programming practice,
therefore it is not advised.
Identifier name can be up to 1023 characters long. However, it changes from
version to version.

BJ DATATYPES
Data types determine the type of value that can be stored in a variable. It describes
about the spac~ccupie.dJ:zy_a variable. in storage. It is a good programming practice to
use data types according to the size requirements for reducing the speed of execution
of programs. The types defined in the VB.NET fall into two categories.
m_____ PiowametttAfs~~

. ' V~ue type variables_jiold actual data. T~ey are assigned_stackmory. Y~ue tyJ)c
mcluaes all numeric data types, Boolean, Char and Date. Us~r defined data type is al
considered value type even if its members are of reference type. Default values for va}u_&o
types are different. For example, all numeric and Char data types have default value 0c
While Boolean has default value as False. Date has default value as 0:00:00 (midnighq
on January 1, 0001. The default value of a user defined data type consists of the
combination of the default values of each of its members.
~ fere.!!:e Type variahles} point to the data inste_ad of actual holding data..:...-They ar.t
assigned heap mell!_~IY- Reference type includ-es String, Array and Class types s:.ich aa
re:..:n.:.:c:..=e...:. ._ _ _ _____
=:.: .:::e.:..:
Form class. Default value for reference types is --=1-=-r.ei
Data Types further may be categorized into umeric and non-numeri data types
depending upon their usage.

(i) Numeric Data Types

Numeric data types contain data consisting of numbers that can be computed
mathematically. The numeric data types include Integer and Floating-point data types
All numeric types are of value typJ . Various numeric data types available in VB.NET
are given in Table 2.3.
Integer Data Types: The integer data types are used for storing whole numbers i.e.
numbers without fractional parts. Integer values can be signed or unsigned . Signed
numeric data types are used to store both positive and negative values. While unsigned
can store only positive values. ·
Floating point Data Types: Single and Double data types are used for high
precision calculation. Single data types provide 6 digits of accuracy while double types
provide 14 digits of accuracy. These data types are generally used in scientific
applications.
Decimal Data Types: Decimal data types hold a binary integer value, together with
a sign bit and an integer scaling factor that is used to specify the portion of the value
as a decimal fraction.

Table 2.3: VB.NET Numeric Data Types

Data Type .NET CTS TYPE Storage Range


A. Numeric Data Type : Signed Integer
SByte System.SByte 8 bits or 1 byte -127 to 128
Short System.lnt16 16 bits or 2 bytes -32,768 to 32,767
Integer System .In t32 32 bits or 4 bytes 2,147,483,648 to
2, 147,483, 647
Long System.lnt64 64 bits or 16 -9,223,372,036,854,775,808 to
bytes 9,223,372,036,854,775,807
Fmwamenta~ of VB.NET

B. Numeric Data Type : Unsigned Integer


Byte System.Byte 8 bits or 1 byte Oto 255
UShort System. Ulntl 6 16 bits or 2 bytes Oto 65,535
Ulnteger System. Ulnt32 32 bits or 4 bytes Oto 4,294,967,295
ULong System.Ulnt64 64 bits or 16 bytes Oto 18,446,744,073,709,551,6 15
C. Numeric Data Type : Floating-Point
Single I
System.Single 32 bits or 4 bytes -~.4028235E+38 to -l.401298E-45
for negative values;
J.401298E-45 to 3.4028235E+38 for
.positive values
Double System.Double - 64 bits or 8 bytes Cl.7976931348623 1570E+308 to -
r .94065645841246544E-324, for
egative values
4.94065645841246544E-3 24
through
l.79769313486231570E+ 308, for
ositive values
D. Numeric Data Type :\~ecimal
Decimal System.Decimal 128 bits or 16 pto+/-
bytes . _ 79,228, 162,514,264,337,593,543 ,95
0,335 (+/-7.9 ... E+28) with no
decimal point;
0 to +/-
7.9228162514264337593 54395033
5 with 28 places to the right of the
decimal

(ii) Non-Numeric Data Types


Char, String, Date, Boolean, user-defined and Obje~data types are used for
managing Non-numeric data: Such. data ca.rffiot be used in mathematical operations
u sing standard arithmetic operatorsJ Char, Boolean~user-defined and Date are of value
type, while Sgjng and obje,Sl..are of r~ ere?ce type. The data types supporting non-
numeric data are given in Table 2.4. · r-- -

Table 2.4: Non-Numeric Data Types

Data Type .NET CTS TYPE Storage ~ge


Char System. Char 2 _bytes / 0 through 65~5 (unsigned)
Date System.DateTime 8 bytes / 0:00:00 (midnight) on January, 1,
r - 0001 through 11:59:59 PM on
December .3 1 , 99f t
--
m ~ta t& ~
System.Boolean Platform True or False values
Boolean
Dependent
Object System.Object 4 bytes on 32- Any data type can be stored in a
bit platform variable of data type Object
8 bytes on 64-
bit platform
String System.String Varies O to approximately 2 billion Unicoctc
charac ters
User- Inherits from Platform Each member of the structu re has a
Defined System.ValueType Dependent range determined by its data type
and is independent of the ~ es of
the other members

Bl LITERALS
A literal is a fixed value that cannot be changed. Literals in VB.NE
T compr ise of
also call
series of charac ters like digits, letters etc. Loosely speaking, Literals are
its va1
consta nts. But a consta nt ·is comparable to a regula r variable except that
----=--
canno t be modified after its defini tion;o r example, the numbe r 10 and
the sni1
"'Hello VB.NET" are both literals. ·
to
Data type of numer ic literals is d~lare d by append ing a type declar ation charac
number ij
or suffix. If type declaration ch~ct er is not specified, then any whole
suffl.X'I
consid ered as Integer, while decimal numbe rs are considered Double. These
The ~
are used so that VB.NET can handle the calculations more accura tely.
declaration charac ters for numer ic literals are given in Table 2.5.
Table 2.5: Type Declaration Character

Data Type Type declaration Character or Suffix


Short s
Integer I or%
Long Lor &
Single F or!
Double R or#
Decimal Dor@

(i) Intege r Literals

An Intege r literal is a whole numbe r. A minus sign can be used


optionally to
side, any
repres ent negative values. Spaces , comm as, dollar sign, sign at the right
le,
specia l or non-digit symbol are not allowed in an intege r literal. For ex..unp
Valid: 243 -243 2431 123456781

Invalid: 24,3 24 3 243- $243


Futtaamenta~ of VB.NET

(ii) Floating point and Decimal Literals


Floating Point and Decimal literals (Real literals) are used to represe nt values that
vary continu ously like distanc e, tempera ture, height, width, time in analog
clock ere":
These values are represe nted in decimal notation or in exponen tial notation.
Expo_n~ntial literal ~ e also. called floating point literal as one can change y1o~ e
posi~?~ 0 c1m pomt by mcr~a · _ _ecr~asmg :_x_eone nt valu~ ci":a- n~ta~on
con,tam s a who)e number , a decunal p..Qint and a fractional~ Expone ntial nota tion
is used for repr..:se nting very small or large values. This notation comprises of two
l
compon ents: Mantiss a7and § xponen t} Mantissa can be an integer or a decimal
number . Letter 'e' or 'E' separat es. the mantiss a and the exponent part. The expone nt
value may be a positive integer for' representing very large values or a negative integer
for r~prese nting very small valuesJ 'E2' means multiply the value by 10 or 'E3' means
2

multiply the value by 103 • Examples of these literals are as follows .


Single 9.723F -78.8F or -78.8!
It • . 65.70R -58.9R or -58.9#
I . I • 450.67D -99.99D or -99.99@
2.6575e2 0.36575e3

(iii) String Literals


A string literal is a se uence of charact ers, digits or special charact ers enclose
d
between double quotes. If quotation marks are to be used inside a string literal, they
must be used twice together and will be interpreted as one symbol. For example,
"I said,""Go Out"" " "Rita" "z"

. "123AN" "Lipakshi Arora" "999"

(iv) Character Literals


A charact er literal may be a single digit, charact er or symbol enclose d in double
quotes followed by C, which is a literal type charact er to identify a string literal as of
char literal. For example,
"OC" "dC"

(v) Date and Time Literals


Date and Time literals are used to store date and time values. These literals are
enclosed within two # symbols. For example,
#8-Jan-00# #4:00 pm#

fD VARIABLES
Besides working with the Text propert y of TextBoxes and Labels, tempora ry results
e
of multi step calcula tions are required to be stored in some locations. This is possibl
~
with the help of variables. ~ variable refers to a memory location that can co!!_!a_!!} _
Fiuwamenta~ ~ VB.~
data value _which_can..be-changed during project execution. A variable in VB.NET _
always a data type. - - ----....__ ha.~
---
I

(i) Variable Naming Rules I I

. The variabl~ name can con~ain numbers, letters and the underspore character, but I
1
1t must start with a letter. Though underscore can ,be used as first character, it is not I
supported by CLR. So, it should be avoided. -.
/ '
-Reserved
, keywords cannot be used as VB.NET
. Variable name.
· ~White spaces cannot be used in a variable name .
..)ff NET ~ariable names ar{ not case sensitive _1
The maximum length of a variable name can be 1023 including fully qualified
name. It also varies from version to version.

(ii) Declaring a Variable

V~ es ~ eclared...using pIM=-sta~emen~ which can be used at module, class,


structure, procedure level or block level.@}eclaration statement of a vari_able describes
about the name of the variable, its d~!a type and ~coe!:_,qi the-variag,le~upon
the location where it is declarec!_J A~ alue can be assigned durl'ng declaratiop or later
on whenever required but before e actual usage of the variable. The syntax of
declaring a variable is as foliows. .. ,
Dim Variable_Name [As Data Type]
Where keyword, Dim, is derived from dimension word whose meaning is size. It is
optional to specify data type. ~f no data_JyJ)_e_ i ~tjon~!i$!!.....i.!_~~:!,_data
type. Examples of declaring varia6les are as follows.
Dim i As Integer
Dim counter, total As Integer
Dim DOB As Date
Dim Flag As Boolean ,
~rings can be declared as fixed _o r variable length-~ ~ ~he syntax for declarin~1
a fixed-length Stnng is as follows.
Dim VariableName As String* n 'where n defines the length of fixed- length string
Examples of declaring String variables are as follows.
--- - ~
Dim name As String · for v~ g ~---
Dim MyName, usemame As String 'for variable length strings
Dim MyName As String *10 ' MyName can hold maximum 10 characters

(iii) Assigning a Value to a Variable


A variable can be assigned a _value using assignment operator (•) ei;:~':I
declaration statement or afterward/ but before its usage. ~ rocess of~
FUn3amentals of VB.NET m
le_Yar iables
value to a variable during declar ation is called initializatio.D oWhe- \laiiab
syntax is as
.,are7t imahz ed with an equal sign followed by a consta nt expres sion. The
follows.
Variable-name=Expression •
The
The _variable .can be a declar ed variable or a control with its proper ty name.
express~on can be a numer ic literal, .. string·· nteral, - Boolean literal, mathe
matical
expres sion or a contro l proper ty value. The examples are as follows .
Dim Stu_lD As Intege r= 11 'Variables initialization during declaration
Dim Stu_Name As String = "Arnav" ' Variables initialization during declaration
Mynum=lO0
Number1=2.3587& ' To assign long integer value
Number2=2.3587! ' To assign single value
Number3=2.3587# ' to assign double value
MyName= "Arnav"
Txt_us ernam e.Text = "Arnav"
Lbl_message.Visible = True 'A property control
Rad_female. checked=True
Lbl_message.Text = Textboxl.Text
Txt_result.Text = Val(Txt_nol.Text)+ Val(Txt_no2.Text)

(iv) Check ing Datat ype of a Variable


examp le,
The metho d GetType() is used to check the data type of a variable. For
data-·type of a variable can be displayed as follows : . 7
MessageBox(a.GetType().ToString())

(v) Optio n Expli cit Statem ent


variab le
If 'Option Explicit On' is used, the VB.NET compiler enforces explicit
However 1C
-~ecl~~tiop whlch_meag§ ~ eryv ariable must)2.e ~d~clared-before it~ tisage.
can be made off, though it is not a good_..Qrogramming practice.7 -

'
(vi) Optio n Strict Statem ent
i.e.
By defaul t, the Visual Basic .NET compiler does not enforce strict data typing
n Strict On'
converting an_y data tJ-p_e .to..an...y_o.ther_data.JY.p.e...implicitly js allowed ,._'Optio
implie-; th at type. checki ng ~wi!5h ~ on.\!_o~~ver \'O~tion Strict On'restricts
implicit
all data type
d'.3-ta type cqrrver$IOQS to. only .wiaen gi.g.,£:Qnvers1on. This means value of s~
or examp le,
can fe_assign ed-to.....a gre_a tec data type but the vice versa is not allowed.:..f
ted_t~_byte.
byte data type can be conver ted to intege r. But intege r canno t be conver
string literal
Similarly literal type charac ter C must be appen ded to a single-charac ter
to identify it as the Char data type.
2.10

Data loss may occur if the value of one data type is converted to a data type haVin
smaller range of values. It throws a run-time error message if data is lost in sue:
conversion. If 'Option Strict On' statement is specified, it gives information about such
conversions at compile time. Option Strict also makes Option Explicit on. The Option
Strict statement must appear before any other code in the code window.
Option Strict/Option explicit can be changed in the following way.
• In Solution Explorer window, select a Project and right click to get Properties
Dialog Box. Or select Project menu and click Properties.
• Click the Compile tab and set the value in the Option Strict box.
• When user creates a new project, the Option Explicit setting on the Compile tab
is set to the Option Explicit setting in the VB Defaults dialog box.
The VB Defaults dialog box can be accessed in the following way.
• Select Tools menu and then click Options. In the Options dialog box,
and Solutions appear in left pane.
• Expand Projects and Solutions. Click VB Defaults in the left pane.
• The initial default setting for option strict appears in right pane.

fD CONSTANTS AND ENUMERATIONS


A constant is a fixed value which cannot be changed during execution o ~,
while an enumeration is a set of const~ts. VB.NET constants and enumerations may
be user defined or system defined.
(i) User Defined or Named constants
A named constant is used in place of a literal value as it is easier to remember a
name than a value. The constant need to be defined once and-can be used in many
places in the code'. It cannot be modified during the execution of the code after it is
defined. After definition, any change in their value- using assignment operator
generates error. /
Such constants are declared using the keyword, Const, which may be used- at
module, class, structure, procedure or block level. Thes-e constants can be of any of the
basic data types such as integer, floating, character or strigg. The data type of a
constant and its value should match-in the definition statement. The syntax of defining
a constant is as follows.
{Modifierj const.a ntname [As datatypet= value
Modifier can be Public, Protectedt- Friend, Protected Friend or Private The modifier
controls the accessibility o(th~s; const~ ts i~ other classes. The ~odifi~r is optional.
For examples, - --------
Const maxval As Long = 9999
Public Const strl As
. String=
,
"Arnav"
Private Const pi As Double = 2.1415
Funoomentals of VB.NET EID
J~ a type is not specified, the constant takes the data tvoe of.lnjtiaJ vaJuc.. :. If
ofh data type and initial value are specified, the data type of irutiaJ value should tx
onvertible to data type specified. If neither data type nor irutial value is specified . the
ata type of constant is of Object data type. If a constant is defined With daiA
e Object, It is assigned the data type of initial value.
Named constants are used for better readability and understanding of a code. ft 1s
ommonly used in scenarios where user has to use a value like 'pi' again and agrun in
program to evaluate expression comprising pi value. Instead of using literal qllu,
.14 repeatedly, the named constant pi can be used for better und~tand.tng nnd
asier maintenance of the code. Since, such constants are defined only once•
erefore, it becomes very easy to modify such values. Moreover, by maJong o sin¢('
hange in the definition statement of the riamed constant, its value is changed nt nil
cations, where it has been used.

i) User Defined Enumerations


An enumeration is a symbolic name for a set of named integer constants For
ample, an enumeration can be declared for a set of integer constants associated ~,th
e months of the year. These names of the months can be used in code rather thnn
eir integer values for better readability and understanding.
m~m_!fil)nths
January = 1 ·/
February= 2

I. •.
__ ___,
nd Enum
Enumerations can be used in code in the following way.
essageBox("The mon~ is:" & Months.January)

ii) Intrinsic constants


Intrinsic constants ·are ~ys~e~ -defined constants which are built-in the
vironment and need not_1.Q...Q~-d~fin~d-~2ffilicitly..,_ VB provides many system-defined
nstants. Few of them are as follows.
The constant~
-- ______~--
r_is used for ~ arriage ;;,.~ character.
The constant vbLf is used for linefeed character. ,

The constant vbCrLf is used for carriage return and linefeed character combination .
.,,. ~ .....,._ r.- --= - - -...... - - ~ · - - - -- - - - --
.. ....
The constant vbNewLine is used for newline character.
The constant vbNullChar is used for null character.
pt

ml Fmwamenta~ of VB~l

m SCOPE AND LIFETIME OF VARIABLES


Scope of a variable means the variable can be seen and µsed j!!__q_Specified locati
wifuout-any eq:or.~.Scope rs·~~-o~-Za.lka-.~bilityof;-;~ab~.h_ich may be for an e~~
project, for <?:le fo~, for one proc~pure pr Ol}lY f~ ?A~ block~ The ? lacement of DlM
statement used for variable dec;Jaration d.ecid.e.~_,!h,Lrj§.iQiJity of a vanable.nThe ~~
of '.3:,,Y~le is the~_p~!_io~ <?f ~~e t~~! t~e,_yzjaql~ ~xist~ ., ""
(i) Namespace Level: A namespace variable is used by~ dtires of 2-11

-
entire project.
. ___
Namespace variables may be.. considered
..-:a~ ~

These are generally used across multiple forms and multiple modules.
~

. as glo_bal variables.
--::::.
- - - -..- w;.:

of a fo~.
~
(ii) Module Level: A module-level variable is_2~~-d_..!?,y all the ..Q[Q.Cedur
Such variables are defined after . the class or module statemen(, but before the first
procedure statemenU.e. in de~l~ati~;;;~tio~--.,-~f the F~rm.Li:'~odule-level varjableii
available till ffie"y'orm is ~ mem2!ij'A module · level variable can be mad~~ tatic to.
retain its value. • #

(iii) Procedure (Loc!l) Level: A local variable is used by the procedures in which it
is declared. The lifetime ofa "Iocalv ariable i; one execuilon- of a proG,edur~
- ....,.__ - - - -
- - I ., :,,_ -

whenever procedure _is . executed; the local variabl~ is defined, . execut~d and
reinitialized again. Numeric variable are reinitialized with O and _§_triri
variables are reinitialized with null reference. After the execution of proced~
memory locations assigned to local variables are released. ~ '
(iv) Block Level: A block variable is ~sed only by the ~to~k ~f _£~de in which it is
declared. The block of code may be an IF... ENDIF, DO ... LOOP, FOR. .. NEXT or any
other block. The variables defined in a block are defined, executed and reinitialized
.,.._ • r,,•• • - - • - •. • ---....

every time a block is executed and released after the execution of block is over:
Now, it is the time to use these basic concepts practically in an exe.rcise. Write a
project in VB.NET to declare variables of different data types, assign appropriate values
and display them. Project 2.1 shows the usage of variables in VB.NET.
Project 2.1: Using Variables

Public Class Forml


Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim varSbyte As SByte
Dim varlong As Long
Dim varDecimal As Decimal
Dim varUshort As UShort
Dim varSingle As Single
Dim varChar As Char
Dim varString As String
Dim varBoolean As Boolean
Pu1wattteKt4f& of ~
-
form are given as follows.
The desi gn time and run time layo uts of the

~ Variable Declaration
-10 is of tytpe System.5Byte
9021927475 is of data type System.lnt64
20394.293 is of dm type System.Dec inwl
293 is of data type System.Ulnt16
29 is of dlta type System.Single
c is of data type System.Char _
VB.NET Programming is of data type System.string
True is of data type Systvn.Boolr.an
31-0S-2018 is of data type System.DileTime

OK

(after clicking on Sho w Values)

m OPERATORS tha~_tel]§__the com_Rl.!,t «:_! tQ_ $do rm. c~~


An ope rato r is dep icte d by a symqol nds dep end ingjupoq
on_e ,_two or _!Pr ee_~pera
mat hem atic al or logical man ipul atio ns on
resu lt:-'\O pera tors ar~ ~_sed eith er to fo!Ill
the type of the ope rato r and -retu rns a able s or exp ress ions . V .N
mat h~ al or logical exp ress ions or to man ipul ate vari
sup port s a rich set of ope rato rs.
ope rato rs ope rate on sing le ope rand For
Ope rato rs may be una ry or binary. Unary
ple, ++ and --. Bin ary ope rato rs ope rate on two ope rand s. All ~th me tic ope rators
exam
of bina ry ope rato rs. Diff eren t types~ /
(except una ry + and una ry -) are examples
ratio ns are liste d below. ✓•
ope rato rs clas_sified on the basi s of thei r ope •
Arit hme tic Ope rato rs
Relational Ope rato rs
Logical Ope rato rs
Assignment Ope rato rs

(i) Ari thm etic Ope rato rs


atic al calc ulat ions and can be used on
. ~th me tic ope rato rs are use d for mat hem
a num ber or valu e whe n use d in an
bu11t-m_ num eric data types. They retu rn
be use d as una ry ope rato rs. Min us unary
express10~. Plus and min us ope rato rs can
a num ber. Diff eren t arit hme tic operators
operator is use d to cha nge the sign of
w in Tab le 2.6.
sup port ed by YB. NET lang uag e are liste d belo
Table 2.6: Arithmetic Operators

Operator Operation Performed Expressions Examples


I\
Exponential c=a "b Let a= 7 and b = 3
(Raises a num ber to the power specified)
PUni}amentals of VB.NET
* Multiplicat ion c=a*b Let a= 7 and b = 3
Then c will be 21

I Division c=a/b Let a= 7 and b = 3


Than c will be 2.333
Integer Division
- Let a= 7 and b = 3
\ c=a\b
(Divides integers and truncates Than c will be 2
remainder, if any)
.
(int data type)
Mod Modulus (Modulo Division) returns the c=a MOD b Let a= 7 and b = 3
remainder of an integer division Than c will be 1

+ Addition or Unary plus c=a+b Let a= 7 and b = 3


Then c will be 10

Subtraction or Unary minus c=a-b Let a= 7 and b = 3


Then c will be 4

Arithmetic expression s are evaluated on the basis of eie1 az chy fo1 der} of operations
o r order of precedenc e. If two operators are of same precedence , then left to right order
is followed. If any expression is enclosed in Earenthese s, ilien it is evaluated first.
Neste d :R_~ nth~ ;es are -;=ol ved inner to ;~t~~rde; . Let°ii;··writ e a project in VB.NET to
-~-.,got'"'~
apply arithmetic operators on two values entered in textboxes and display res~ts in
labe ls of VB.NET form. Project 2.2 shows the usage of arithmetic operators in VB .NET.
Project 2.1 : Using Arithmetic Operators .

Public Class arithmetics


Private Sub btnShow_C lick(sender As Object, e As EventArgs) Handles btnShow.C lick
lblResAdd. Text = Val(txtnol.T ext) + Val(txtno2.T ext)
lblResSub. Text = Val(txtnol.T ext) - Val(txtno2.T ext)
lblResMul. Text = Val(txtnol.T ext) * Val(txtno2.T ext)
lblResRem .Text = Val(txtnol.T ext) Mod Val(txtno2.T ext)
lbllntDiv.T ext = Val(txtnol.T ext) \ Val(txtno2.T ext)
lblResDiv.T ext = Val(txtnol.T ext) / Val(txtno2. Text)
lblResPowe r.Text = Val(txtnol.T ext) "Val(txtno2 .Text)
End Sub
Private Sub btnExit_Cl ick(sender As Object, e As EventArgs) Handles btnExit.Cli ck
Me.Close()
End Sub
1111111111

The output is as follows :


- □
Arithmetic Operations
Result
Operator

Addition(+} 10
Enter First Number 7_______
!'-- j 4
subtraction(·)
Multiply(") 21
\3_ _ _____
Enter Second Number ._
Division(/) 2.333J3333333333
Integer Div.(\) 2
Remainde~mod) 1
Raise to power() 343
Show Exit

(ii) Relational Operators


Relational operators are used to compare the values of the operands of same Gata
type to check whether they are equ~, _one value is greater than the other value or less
than the other value. These operators return either True or Fals~. ,!hese are ge1:erall
used in decision-making statements. During comparison of strings, upper case letters
are less than lowercase letters and number are less than letters. Relational operators
supported by VB.NET language are listed below in Table 2.7.
Table 2.7: Relational Operators

Symbol Operation Performed Expressions Example


< Less than a<b 7<3 returns False
<= Less than or equal to a<=b 7<=3 returns False
> Greater than a>b 7>3 returns True
>= Greater ~an or equal to a>=b 7>=3 returns True
7=3 returns False
<> - - - to
.__ Equal
Not A<> b 7 <>3 returns True
·
in VB ·NET to a PP lY re latlonal
. Now, write a project. operators on two values entered
m Textboxes and display results in Labels of VB NET F . th
u sage of relational operators in VB.NET. . orm. ProJect 2.3 shows e
Fun3amentals of VB.NET

Project 2.3: Using Relational Operators

Public Class relational


Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
lblResless.Text = Val(txtnol.Text) < Val(txtno2.Text)
lblReslesse.Text = Val(txtnol.Text) <= Val(txtno2.Text)
lblResGreater.Text = Val(txtnol.Text) > Val(txtno2.Text)
lblResNote.Text = Val(txtnol.Text) >= Val(txtno2.Text)
lbllntequal.Text = Val(txtnol.Text) = Val(txtno2.Text)
lblResGreatere.Text = Val(txtnol .Text) <> Val(txtno2.Text)
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles bmExit.Click
Me.Close()
End Sub
nd Class
The output is as follows.

Operator Result

EnterFirstNumber 17_ _ ==:J Less Than(<) False


Less flan equal(<•) Fabe
Enler Second Number ~ Grealer lhan (>) True
~-~

Grealerthanequa~>-J True
Equal(-) Falle
Not equal (o ) True

First Number is used on let side of operator

(iii) Logica l Operat ors


Logical operato rs are used to make CJ2JJ1pmmd co~s!i!;ioos. They work on boolean
values (true or false) and returna boolean value. Table 2.8 lists the logical operato rs.
Table 2.8: Logical Operators

Operation Working of Logical


Symbol \ Example
Performed Operator

NOT Logical NOT Returns true if the operand is If 'b = true', the express ion
•fl ,)') JC \ false; oth~~s
' . .
e returns false· 'NOT b' returns false.

AND Logical AND Returns true if both the If 'b=true and c=true' then
operand s are true, otherwise expression 'd=b AND c'
returns false returns true
fjf:i Fmwamentals <?f

OR Logi cal OR Retu rns true if one of the If 'b=tr ue and c=fal se th
oper ands or both the expr essio n 'd=b OR c ' re~ n8
oper ands are true, othe rwis e true
retu rns false .-·
Retu rns true iff only one of
--- If 'b=tr ue and c=tru e then
XOR Logi cal XOR
is true, expr essio n 'd=b XOR c'
the oper and
othe rwis e retur ns false . retur ns false
If 'b=fa lse and c=tru e then
expr essio n 'd=b XOR c'
retur ns true
oper ators on two valu es ente red in
Let us write a proj ect in VB.N ET to appl y logic al
Proj ect 2 .4 show s the usag e of logical
Text boxe s and disp lay resu lts in Labe ls of Form .
oper ator s.
Project 2.4: Ualng Logical Operatora

Publ ic Clas s logic al


tArgs ) Hand les btnS how .Clic k
Priva te Sub btnS how_ Click (send er As Obje ct, e As Even
Dim no 1 As Bool ean
Dim no2 As Bool ean
to bool ean
'bool ean.p arse is used to conv ert strin g (true /fals e)
no 1 = Bool ean.P arse( txtno 1.Text)
no2 = Bool ean.P arse( txtno 2 .Text )
'cboo l conv erts valu e to bool ean (true /fals e)
lblRe sNO T.Te xt = CBoo l(Not nol)
lblRe sAN D.Te xt = nol And no2
lblRe sOR .Tex t = nol Or no2
lblRe sXO R.Text = no 1 Xor no2
End Sub
tArg s) Hand les btnE xit.C lick
Priv ate Sub btnE xit_C lick( send er As Obje ct, e As Even
Me.C lose( )
End Sub
End Clas s
The outp uts for diffe rent valu es are as follo ws .

'- Logical Operations - 0-- ' ,I} Logical Operations - ca


---,
R88IIII Op.alo r Result
Ope,alDr
,---
Enter FIISI !unbar
··- - -·-
•lrue
-- False
Enter Fi:sl Number /we Nol False Not
NC) True ANO False
B1ar Second Number l1rue OR True Enler Second Number /iats-;---· -1 OR True
XOR False XOR True

Show Exit C siiow ] r·-e;-


= == • w :z:::::....z.....mr: ascz m nn,u c:w::a.::;: x:
pun~amentals of ~ .NET

(iv) Assignment Operators


Assignment operators are used to assign the result of an expression or value to a
variable. Its symbol is'='. Table 2.9 demonstrates the use of assignment operator ('=1,

Table 2.9: Use of Assignment Operator '='

Expressions Result
a=l0; Assigns 10 to variable 'a'
a=l0; Evaluates the expression 'a+b' and assigns
b=20;
c=a+b;
value to variable c. In this case,
value ot 30.
-

Apart from '=' assignment operator, VB.NET provides shorthand assignment


--
~ will have

operators also. These are given in Table 2.10.

Table 2.10: Shorthand Assignments Operators

Equivalent Reault
Symbol Operation Performed Example
Construct (x=S

Addition assignment X += 2; X = X + 2; 7

Subtraction assignment X -= 2; X = X - 2; 3

Multiplication assignment X *= 2; X = X * 2; 10
Division assignment X /= 2; x = x / 2; 2.5
Integer Division assignment X \= 2; X =X \ 2; 2
Raises power of value to the x"= 2 x=x*x 25
value given on right side o(
. '
expression
Concatenates twg_y__allJ.es x&= 2 x=x+2 52
and a; signs~r~sJJ,lts
.,_,,_..-- '
jo (as Strings)
vari_able on left side
Now write a code in VB.NET to apply assignment operators on two values entered in
extboxes and display results in labels of VB.NET form. Project 2.5 shows the usage of
ssignment and shorthand assignment operators.

Project 2.5: Using Assignment Operators

blic. Class assignment


Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
'for intermediate calculation for integers
Dim val 1 As Integer
Dim val2 As Integer
PUn3ament.als of VB.NET
flD
val2 = actVal2
val 1 "= val2
lblResPower.Text = vall
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub

nd Class
The output is as follows.

Opeqb ~

Enter Number L .-
- __- -_,
Addion(-) 7
!
EnlerAssignmentValue ..__
2 _ __,
sub•acaon(••l
Mulliply("•)
Division(/•)
3
10
2.5
Int Division(\•) 2
Concalllnate( amp•) 52
C Show J Exit Raise lo power('•) 25

v) Bitwise Operators
Bitwise operators are used to evaluate binary integers bit wise. They compare
itwise and assign the resurt aftehompan soii. Table 2.11 shows Che- various bitwise
perators available in VB.NET.
Table 2.11 : Use of Bitwise Operators

Result
Symbol Operation Explanation baaed on
Example (x=SO,,
Performed r-50 and r-40
y=40)
' '
AND Bitwise AND ~ANDy 32 Bit wise AND operation evaluates to 1,
if both digits are 1s.
y=00 101000 (binary)
x=00 11001 0(binary)
c=~_QQ{_ b_in~) which is 32 in
decimal
OR Bitwise OR XOR y 58 Bit wise OR operation evaluate to 1, if
either digit is 1.
y=00 101000 (binary)
x=00 11001 0(binary)
c=00 11101 0(binary) which is 58d.
Fun~amenta~ ~ VB~

XOR Bitwise XOR X XOR y 26 Bit wise EXCLUSIVE OR opera~


evaluates to 1 if one bit is .9 anct
other is 1.
1
y=00 101000 (binary) 1

x=00 1100 lO(binary) I


'
c=000 1101 0(binary) which is 26ct.
NOT Bitwise NOT NOTx -51 The digit 0 is replaced withl and 1 7
with 0. It also inverts sign bit. 1

x=00 110010 (in binary); After Bitwise


notX;
x=l 1001101 (in binary);
This number is -51 in decimal. Since,
its most significant bit is 1 tha
indicates it as a negative number, s
this number is converted to 211
complement form before converting it
to decimal.
<< Binary Left X«l 100 Inserts 0 from right and left most digit
Shift is removed (once).
x=00 1 10010 (in binary)
after x«l;
x=0l 100100 (in binary) (which is
100d)
This operator moves the bits of
operand to left by the number of bits
specified by the right operand and
adds the same number of zeroes from
the right. I
I

>> Binary Right X»l 25 Inserts 0 from left and right most digit
Shift is removed (once).
x=00 110010 (in binary)
after x» 1;
x=000 11001 (in binary) (which is 25d)
This operator moves the bits of
operand to right by the number of bits
specified by the right operand and
adds the same numb~r of zeroes frorn
the left.
Now, write code in VB.NET to apply bitwise operators on two values entered in
Textboxes and display results in Labels of Form. Project 2 .6 shows the source code. I '
I•'

111111.....___
Fun3amentals of VB.NET

Project 2.6: Using Bit wise Operators

Public Class bitwise


Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim vall As Integer
Dim val2 As Integer
vall = Val(txtnol.Text)
val2 = Val(txtno2.Text)
lblResAnd .Text = vall And val2
lblResOr.Text = vall Or val2
lblResXOR.Text = vall Xor val2
lblResRight.Text = vall >> 1
lblResLeft .Text = vall << 1
lblResNOT.Text = Not vall
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
The output is as follows.

Operator Result

Enter First Number 50_ _ _~


'--/ Bilewise AND 32
Bitwise OR 58
Enter Second Number _ _ _~
'-j40 BltwiseXOR 26
Bitwise NOT -51
Bitwise Left Sh~1 bit) 100
Bitwise Right Shift(1 bit) 25

IL.._....... Show-·········· 1/ Exit J

fE OPERATORS PRECEDENCE AND ASSOCI ATMTY


Every language has well defined rules for evaluating expressio n comprisin g multiple
operands and operators . When more than one operator has to be evaluated in an
fBI . . .. FH>Wat!tentak ~~
expression, precedence and associativity rules help m dec1dmg which operator sh
be evaluated first. Precedence is the priority order of an operator among operator 0~
. s \.l~
i~ an expression. Highest order priority operator is execute_d first the~ higher anct th
high. For example, consider an expression, '2 + 3 * 6 . In this express10n, multiplieau~
1

(*) operator will be processed first and then addition operator. This is due to VB.N;
operator precedence in which multiplication operator has higher priority over additi
operator. In other words, when an operand is shared by two operators (e.g. 3 is shaxflt
by + and *) then higher priority operator chooses the shared operand for process·
So, the role of precedence or priority is very important in execution of operators.
Associativity tells the d.irection_of. execution oJ _operators in case all_operators in
expression have same priotity._Associativity can be either 'left to right' or 'right to 1
The priority of a VB.NET operator c.an also be changed by enclosing the lower or
priority operator in pare;theses. Assodativity ~~~o; be ~hanged.
• - ... --.✓ ... __ ~.._ -.....:.-_q

For example,
- ---,

expression (2 + 3) * 6 1 addition will be done first because parentheses have hi


priority than multiplication operator. The developers should take extra care a
precedence and associativity rules while writing programs. Table 2.12 summarizes
VB.NET operator precedence and associativity. The precedence with lowest value
given highest priority.

Table 2.12: VB.NET Operator Precedence and Associativity

Order of
Operator Operation Performed Associativity
Precedence
Await Used in multithreading 1
A
Exponential 2 Left to Right
+ Unary identity, 3 Left to Right
Unary Negation
* Multiplication, 4 Left to Right
I Float Division
\ Integer Division 5 Left to Right
Mod Modulus (Modulo Division) 6 Left to Right
+ Addition 7 Left to Right
Subtraction
& String concatenation 8 Left to Right
<<,>> Arithmetic bit shift 9 Left to Right
= <> Relational Operators 10 Right to Left
and ------------- -
Funwnentals of VB.NET

other comparison operators


compares references
Is Not
Like TypeOf
Negation 11 Left to Right
Logical AND 12 Left to Right
Logical OR 13 Left to Right
Logical XOR 14 Left to Right

2.10 CONCATENATING STRINGS


using
Joinin g of two strings is called concat enatio n. The concat enatio n can be done
all the
pers8!!"?_1~~ 3~:!~I-£t -"!:,JH2fil:~'f2I :.. Tfie concat enate symbol + is used when
operan d 1s
perand s are of string data types. If one of the operan d is non-st ring, the
equire d- t? _be~.:7 .:..t !ed _int~ ~trin& The SWQ.QLVL Y.§i !~eRC>peran
ds ~ e or_
data type.
ifferent types. In this case, there is no need to convert an operan d to string
fhe syntax1s as follows.
Variab lel = variable2 + variable3
'variable2 and variable3 are required to be string.
Variable 1 = variable2 & variable3
'variable2 and variable3 may be of any type.
entere d
Write a Projec t in VB.NET to apply concat enatio n operat ors on two values
the use of
in textbo xes and displa y results in labels of VB.NET form. Project 2.7 shows
& and + operat or for concat enatin g strings .
Project 2.7: Concatenating Strings

Public Class concat e


w.Click
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnSho
Dim val 1 As Integer
vall = Val(txtno2.Text)
'val 1 is converted to string in case + is used
lblResAdd.Text = txtnol. Text + + Str(vall)
11 11

11 11

lblResSub.Text = txtnol. Text & & vall


End Sub
Private Sub btnExit_Click(sender As Object , e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
m Control st~
It is a general practice to execute programs statements sequentially in the Ord
th eir appearance. There are situations where user wants to make choices or want toer Of
.

the same task repetitively. In such situations, instructions should be executed on t~o
basis of choices made rather than sequential order. This is possible in any langu e
with the help of Control Constructs or Structures. The statements which are used ~e
decision making, re·p eating the tasks or branching are also called Control Flo;
statements. These statements break up the flow of execution and conditionally execute
blocks of code depending upon the outcome of specified conditions. They help in
writing small, simple and structured programs. These statements can be classified into
three categories :
(i) Decision-making/Selection structures
(ii) Looping/Iteration Structures
(iii) Branching Statements

DJ DECISION-MAKING OR SELECTION STRUCTURES


Decision-making or selection structures control the program flo..y on the basis of
- ----
outcome of some e?g>ression or condition
... ,-... -
- - -
_______
- ---:----->
- _ , _ _relational and. logical
Iha.de t:i"sing arithmetic,
ope~~tors. Generally conditions are based on our thought process. For example, ififis'
~

raining ou!§ide, you will go out, else you will sit at home. Similarly in programming
languages; on the basis of actual values, conditions are evaluated and different set of
statements are executed depending upon the result of evaluated conditions. If result is
true, a certain set of statements is executed and if it is false, another set of statements
is executed. The decision making structures are helpful in validating data and
controlling tfie flow of program execution.
VB.NET provides following decision-making structures.
(i) If.. ..Then ...End If
(ii) ff ... Then ... Else ... End If
(iii) If... .Then .... Elseif...End If
(iv) Select.. .case
(v) Immediate if (IIF)

3 .1.1 If.. .Then ... End If Selection Structure


The if-then statement is the most basic of all the control flow structures. It allows
the program to execute a block of code only if a given condition evaluates to true. If this
condition evaluates to false , no action is performed and control jumps to the end of
the if-then statement i.e. to the next-statement. The block of VB.NET code may contain
a single or group of statements and the condition may contain simple or complex
xpression. The flow of 'If statement is shown in Figure 3.1 and the general form of "if'
tement along with VB.NET code snippet is shown below.
control Structures flJ
syntax
If <condition> Then
<Block of VB.NET statements>
End If
Code Snipp et
Dim myNumber As Integer
myNumber = TextBoxl.Text
If myNumber >= 100 Then
Label2.Text ="Congratulation! Full Score"
End If

Figure 3.1: lf... then...End IF Statement

True

False Block of VB
Statem ents

Next-S tateme nt i + - - -....J

3.1.2 If... Then ... Else ... End If Select ion Structure
If... Then ... Else is an extens ion of simple 'If selection structu re. It provid
es anoth er
g contro l to
path of execut ion when an 'If condition evaluates to false before movin
paths. If the
next-s tateme nt. In simple words , If... Then ... Else provides two alternative
lock is
condition evalua tes to true, · the true-b lock is executed, otherw ise false-b
'IL . Then ...
executed and then contro l is passed to the next-s tateme nt. The flow of
.Then ... Else
Else' statem ent is shown in Figure 3.2. The general form of a simple lf..
statem ent along with VB.NET code snippe t is shown as follows.
Syntax
IF condition THEN
<Statements of true block>
Else
<Statements of false block >
End if
Next-statement
Code Snippet
D'im myNumber, MyAge As Integer
MyAge = TextBoxl.Text
Di'M N~~) MVJ-M_'l..
myNumber = Te>..'tBox2.Text
N ~ 1. ; T,d bo ~ I ' r~; I ( aj
If myNumber > 100 And myAge > 60 Then Ncvt,\ L_ ~ fr·!hQ X .~ •re b 1·
1

Else
Label2.Text =" Congratulation! Full Score"
t{ Nu:W'- J >~hvM l... T1-»1
Label2.Te>-.1: =" Put more efforts"
End If
i •l r,,_1 -;~L'1x,:~._.,1:. / ~, 1
~1~
Figure 3.2: lf... Then ...Else... End If Statement

r1 ~ t -~
False True

False-block True-block

'----..i Next-Statement ,..___ __,

Now, write a code in VB.NET using console application which takes user input an
checks whether it is less than 20 and prints a message accordingly. Project 3.1 sho
the usage of If.. .Then ... Else control structure.

Project 3.1: Using If... Then... Else... End If Control Structure

Module modlf · for console Application


Sub Main()
Dim a As Integer
Console.WriteLine("Enter the number")
a = Console.ReadLine()
If a< 20 Then
Console. WriteLine("a is less than 20")
Else
Console.WriteLine("a is not less than 20")
End If
Console. Read Key()
End Sub
End Module

You might also like