Chap 2 and 3
Chap 2 and 3
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.
*== 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.
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.
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.
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
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
. 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.
'
(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.
I. •.
__ ___,
nd Enum
Enumerations can be used in code in the following way.
essageBox("The mon~ is:" & Months.January)
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
-
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
~ 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
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 .
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
Operator Result
Grealerthanequa~>-J True
Equal(-) Falle
Not equal (o ) True
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
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.
-
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.
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~
>> 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
Operator Result
(*) 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,
- ---,
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
11 11
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
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)
True
False Block of VB
Statem ents
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
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.