Unit 3: Programming in Visual Basic - Knowledge · PDF fileUnit 3: Programming in Visual Basic...
Transcript of Unit 3: Programming in Visual Basic - Knowledge · PDF fileUnit 3: Programming in Visual Basic...
Unit 3: Programming in Visual Basic .Net 1
Prof Sushant. Sundikar Visual Basic .Net
Unit 3: Programming in Visual Basic .Net
Contents
• Data Types
• Keywords
• Declaring variables and constants
• Operators
• Understanding Scope and accessibility of variables
• Conditional Statements – If-Then, If-Then-Else, Nested If, Select Case
• Looping Statements – Do Loop, For Loop, For Each-Next Loop, While Loop
• Arrays-Static and Dynamic
Visual Basic Statements
A Visual Basic statement is a complete instruction. It can contain:
• keywords—Words reserved for Visual Basic's use.
• operators—Symbols used to perform operations, like +, which performs addition operations; -,
which performs subtraction operations; and so on.
• variables—Symbolic names given to values stored in memory and declared with the Dim
keyword. For example, if you've declared a variable named temperature as an Integer type, you
can store integer values like 72 or 83 in it.
• literal values—Simple values, like 5 or "Hello."
• constants—The same as variables, except that constants are assigned a value that cannot then
be altered.
• expressions—Combinations of terms and/or keywords that yield a value. For example, if the
variable temperature holds the value 72, then the expression temperature + 3 yields the value
75.
Data Types
Visual basic supports a large range of data types. Following are the list of available data types in visual
basic.
Type Storage size Value range
Boolean 2 bytes True or False
Byte 1 byte 0 to 255 (unsigned)
Char 2 bytes 0 to 65535 (unsigned)
Unit 3: Programming in Visual Basic .Net 2
Prof Sushant. Sundikar Visual Basic .Net
Date 8 bytes January 1, 0001 to December 31, 9999
Decimal 16 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point;
7.92281625142643 37593543950335 with 28 places to the right of the
decimal; smallest non-zero number is 0.00000
00000000000000000000001
Double 8 bytes -1.79769313486231E+308 to -4.94065645841247E-324 for negative
values; 4.94065645841247E-324 to 1.79769313486231E+308 for positive
values
Integer 4 bytes -2,147,483,648 to 2,147,483,647
Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Object 4 bytes Any type can be stored in a variable of type Object
Short 2 bytes -32,768 to 32,767
Single 4 bytes -3.402823E to -1.401298E-45 for negative values; 1.401298E-45 to
3.402823E for positive values
String Depends on
implementing
platform
0 to approximately 2 billion Unicode characters
Converting between Data Types
In this case, Option Strict is turned on, Visual Basic will not automatically convert data types when you
assign a value of one type to a variable of another, so it'll have problems with conversion of types, for
example when I assign a double precision floating point variable to an integer variable the system will
give an error message. To fix this problem, we have to do a specific type conversion. Here's the list of
conversion functions you can use in VB.Net:
• CBool— Convert to Bool data type.
• CByte— Convert to Byte data type.
• CChar— Convert to Char data type.
• CDate— Convert to Date data type.
• CDbl— Convert to Double data type.
• CDec— Convert to Decimal data type.
• CInt— Convert to Int data type.
• CLng— Convert to Long data type.
Unit 3: Programming in Visual Basic .Net 3
Prof Sushant. Sundikar Visual Basic .Net
• CObj— Convert to Object type.
• CShort— Convert to Short data type.
• CSng— Convert to Single data type.
• CStr— Convert to String type.
The Option and Imports Statements
Two additional statements that are very important to know about when constructing programs are the
Option and Imports statements. The Option statement sets a number of options for your code, and the
Imports statement imports namespaces into your code, making them more readily available.
Option Statements
You use Option statements to set the "ground rules" for your code, helping prevent syntax and logic
errors. Here are the possibilities:
• Option Explicit— Set to On or Off. On is the default. Requires declaration of all variables before
they are used (this is the default).
• Option Compare— Set to Binary or Text. This specifies if strings are compared using binary or
text comparison operations.
• Option Strict— Set to On or Off. Off is the default. When you assign a value of one type to a
variable of another type Visual Basic will consider that an error if this option is on and there is
any possibility of data loss. In that case, you must use explicit conversion functions to typecast a
value to another type.
Note: Use Option statements as the first line in code.
Option Strict Off
Module Module1
Sub Main()
Dim a As Integer
a=CInt(System.Console.ReadLine())
System.Console.WriteLine("Value of A is" & a)
End Sub
End Module
Imports Statements
Imports statement is used to import a namespace in your program, so you don't have to qualify items in
that namespace by listing the entire namespace when you refer to them. For example, instead of writing
System.Console.WriteLine(“Hello World”) in a program. You can first use the Imports statement to
include System namespace and then can use the following statement Console.WriteLine(“Hello
World”)
Following snippet show the use of Imports statement:
Unit 3: Programming in Visual Basic .Net 4
Prof Sushant. Sundikar Visual Basic .Net
Imports System
Module Module1
Sub Main()
Console.WriteLine("Hello from Visual Basic")
End Sub
End Module
Keywords
As with all programming languages, Visual Basic is built using keywords Table 3.1 shows the keywords
used in VB.Net. These keywords are reserved for use by Visual Basic, and you use them to build your
programs.
Table 3.1: The Visual Basic keywords.
#Const #If…Then…#Else & &= *
*= / /= \ \=
^^= + += = -=
Add AddHandler AddressOf Alias And
AndAlso Ansi AppActivate As Asc
AscW Assembly Auto Beep Boolean
ByRef Byte ByVal Call CallByName
Case Catch CBool CByte CChar
CDate CDbl CDec Char ChDir
ChDrive Choose Chr CInt Class
Clear CLng Close CObj Command
Const Count CreateObject CShort CSng
CStr CType CurDir Date DateAdd
DateDiff DatePart DateSerial DateString DateValue
Day DDB Decimal Declare Default
Delegate DeleteSetting Description Dim Dir
Do Double Each Else ElseIf
End Enum Environ EOF Erase
Erl Err Error ErrorToString Event
Exit ExternalSource False FileAttr FileCopy
FileDateTime FileGet FileLen FileOpen FilePut
FileWidth Filter Finally Fix For
FormatCurrency FormatDateTime FormatNumber FormatPercent FreeFile
Friend Function FV Get GetAllSettings
GetAttr GetChar GetException GetObject GetSetting
GetType GoTo Handles HelpContext HelpFile
Hex Hour If IIf Implements
Imports In Inherits Input InputBox
InputString InStr InStrRev Int Integer
Interface IPmt IRR Is IsArray
IsDate IsDBNull IsError IsNothing IsNumeric
Unit 3: Programming in Visual Basic .Net 5
Prof Sushant. Sundikar Visual Basic .Net
IsReference Item Join Kill LastDllError
LBound LCase Left Len Let
Lib Like LineInput Loc Lock
LOF Long Loop LSet LTrim
Me Mid Minute MIRR MkDir
Mod Module Month MonthName MsgBox
MustInherit MustOverride MyBase MyClass Namespace
New Next Not Nothing NotInheritable
NotOverridable Now NPer NPV Number
Object Oct On Option Optional
Or OrElse Overloads Overridable Overrides
ParamArray Partition Pmt PPmt Preserve
Print PrintLine Private Property Protected
Public PV QBColor Raise RaiseEvent
Randomize Rate ReadOnly ReDim Region
Rem Remove RemoveHandler Rename Replace
Reset Resume Return RGB RmDir
Rnd RSet RTrim SaveSetting Seek
ScriptEngine ScriptEngine ScriptEngine ScriptEngine Second
BuildVersion MajorVersion MinorVersion Select Set
SetAttr Shadows Shared Shell Short
Single SLN Source Space Spc
Split Static Step Stop Str
StrComp StrConv StrDup String StrReverse
Structure Sub Switch SYD SyncLock
SystemTypeName Tab Then Throw TimeOfDay
Timer TimeSerial TimeString TimeValue To
Today Trim True Try TypeName
TypeOf UBound UCase Unicode Unlock
Until Val Variant VarType VbTypeName
WeekDay WeekDayName When While With
WithEvents Write WriteLine WriteOnly Xor
Year
Declaring Variables
Variables are used to store some data in your program—so you need to declare some variables. Unlike
VB6 and earlier versions of Visual Basic, you must declare all variables before using them by default in
VB .NET, and you can do that with the Dim statement (which originally stood for dimension, as when
you set the dimensions of an array); this statement is used at module, class, structure, procedure, or
block level:
[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend |
Private | Static }] [ Shared ] [ Shadows ] [ ReadOnly ] Dim [ WithEvents ]
name[ (boundlist) ] [ As [ New ] type ] [ = initexpr ]
Unit 3: Programming in Visual Basic .Net 6
Prof Sushant. Sundikar Visual Basic .Net
Here are the parts of this statement:
• attrlist—A list of attributes that apply to the variables you're declaring in this statement. You
separate multiple attributes with commas.
• Public—Gives variables public access, which means there are no restrictions on their
accessibility. You can use Public only at module, namespace, or file level (which means you can't
use it inside a procedure). Note that if you specify Public, you can omit the Dim keyword if you
want to.
• Protected—Gives variables protected access, which means they are accessible only from within
their own class or from a class derived from that class. You can use Protected only at class level
(which means you can't use it inside a procedure), because you use it to declare members of a
class. Note that if you specify Protected, you can omit the Dim keyword if you want to.
• Friend—Gives variables friend access, which means they are accessible from within the program
that contains their declaration, as well as from anywhere else in the same assembly. You can use
Friend only at module, namespace, or file level (which means you can't use it inside a
procedure). Note that if you specify Friend, you can omit the Dim keyword if you want to.
• Protected Friend—Gives variables both protected and friend access, which means they can be
used by code in the same assembly, as well as by code in derived classes.
• Private—Gives variables private access, which means they are accessible only from within their
declaration context (usually a class), including any nested procedures. You can use Private only
at module, namespace, or file level (which means you can't use it inside a procedure). Note that
if you specify Private, you can omit the Dim keyword if you want to.
• Static—Makes variables static, which means they'll retain their values, even after the procedure
in which they're declared ends. You can declare static variables inside a procedure or a block
within a procedure, but not at class or module level. Note that if you specify Static, you can omit
the Dim keyword if you want to, but you cannot use either Shadows or Shared.
• Shared—Declares a shared variable, which means it is not associated with a specific instance of
a class or structure, but can be shared across many instances. You access a shared variable by
referring to it either with its class or structure name, or with the variable name of an instance of
the class or structure. You can use Shared only at module, namespace, or file level (but not at
the procedure level). Note that if you specify Shared, you can omit the Dim keyword if you want
to.
• Shadows—Makes this variable a shadow of an identically named programming element in a
base class. A shadowed element is unavailable in the derived class that shadows it. You can use
Shadows only at module, namespace, or file level (but not inside a procedure). This means you
can declare shadowing variables in a source file or inside a module, class, or structure, but not
inside a procedure. Note that if you specify Shadows, you can omit the Dim keyword if you want
to.
Unit 3: Programming in Visual Basic .Net 7
Prof Sushant. Sundikar Visual Basic .Net
• ReadOnly—Means this variable only can be read and not written. This can be useful for creating
constant members of reference types, such as an object variable with preset data members. You
can use ReadOnly only at module, namespace, or file level (but not inside procedures). Note
that if you specify Shadows, you can omit the ReadOnly keyword if you want to.
• WithEvents—Specifies that this variable is used to respond to events caused by the instance
that was assigned to the variable. Note that you cannot specify both WithEvents and New in the
same variable declaration.
• name—The name of the variable. You separate multiple variables by commas. If you specify
multiple variables, each variable is declared of the data type given in the first As clause
encountered after its name part.
• boundlist—Used to declare arrays; gives the upper bounds of the dimensions of an array
variable. Multiple upper bounds are separated by commas. An array can have up to 60
dimensions.
• New—Means you want to create a new object immediately. If you use New when declaring an
object variable, a new instance of the object is created. Note that you cannot use both
WithEvents and New in the same declaration.
• type—The data type of the variable. Can be Boolean, Byte, Char, Date, Decimal, Double,
Integer, Long, Object, Short, Single, or String; or the name of an enumeration, structure, class,
or interface. To specify the type, you use a separate As clause for each variable, or you can
declare a number of variables of the same type by using common As clauses. If you do not
specify type, the variable takes the data type of initexpr. Note that if you don't specify either
type or initexpr, the data type is set to Object.
• initexpr—An initialization expression that is evaluated and the result is assigned to the variable
when it is created. Note that if you declare more than one variable with the same As clause, you
cannot supply initexpr for those variables.
Declaring Constants
You declare constants in Visual Basic with the Const statement, which you can use at the module, class,
structure, procedure, or block level to declare constants for use in place of literal values:
[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend |
Private }] [ Shadows ] Const name [ As type ] = initexpr
• Here are the various parts of this statement:
• attrlist-A list of attributes that apply to the constants you're declaring in this statement. You
separate multiple attributes with commas.
• Public-Gives constants public access, which means there are no restrictions on their
accessibility. You can use Public only at module, namespace, or file level (which means you can't
use it inside a procedure). Note that if you specify Public, you can omit the Dim keyword if you
want to.
Unit 3: Programming in Visual Basic .Net 8
Prof Sushant. Sundikar Visual Basic .Net
• Protected-Gives constants protected access, which means they are accessible only from within
their own class or from a class derived from that class. You can use Protected only at class level
(which means you can't use it inside a procedure), because you use it to declare members of a
class. Note that if you specify Protected, you can omit the Dim keyword if you want to.
• Friend-Gives constants friend access, which means they are accessible from within the program
that contains their declaration, as well as anywhere else in the same assembly. You can use
Friend only at module, namespace, or file level (which means you can't use it inside a
procedure). Note that if you specify Friend, you can omit the Dim keyword if you want to.
• Protected Friend-Gives constants both protected and friend access, which means they can be
used by code in the same assembly, as well as by code in derived classes.
• Private-Gives constants private access, which means they are accessible only from within their
declaration context (usually a class), including any nested procedures. You can use Private only
at module, namespace, or file level (which means you can't use it inside a procedure). Note that
if you specify Private, you can omit the Dim keyword if you want to.
• Shadows-Makes this constant a shadow of an identically named programming element in a base
class. A shadowed element is unavailable in the derived class that shadows it. You can use
Shadows only at module, namespace, or file level (but not inside a procedure). This means you
can declare shadowing variables in a source file or inside a module, class, or structure, but not
inside a procedure. Note that if you specify Shadows, you can omit the Dim keyword if you want
to.
• name-The name of the constant. You can declare as many constants as you like in the same
declaration statement, specifying the name and initexpr parts for each one. You separate
multiple constants with commas.
• type-The data type of the constant. Can be Boolean, Byte, Char, Date, Decimal, Double, Integer,
Long, Object, Short, Single, String, or the name of an enumeration. Note that you must use a
separate As clause for each constant being defined. Note also that if type is Object, initexpr
must be Nothing.
• initexpr-An initialization expression. Can consist of a literal, another constant, a member of an
enumeration, or any combination of literals, constants, and enumeration members.
Comments
A single−quote character (') represents Visual Basic comments, or you can use the keyword REM.
Comments can begin anywhere on a source line, and the end of the physical line ends the comment. The
compiler completely ignores the characters between the beginning of the comment and the comment
line's terminator. The following code shows several comments:
'Hello program.
'This program writes "hello " to the console.
Module Hello
'Use hello when you mean goodbye
Unit 3: Programming in Visual Basic .Net 9
Prof Sushant. Sundikar Visual Basic .Net
Sub Main() 'This method must be named "Main".
Console.WriteLine("hello ")
End Sub
End Module 'goodbye
Identifiers
An identifier is the name you give an element so that the code providers (we, the developers), the code
consumers (also we, the developers), and the compiler can identify it throughout the application. Visual
Basic identifiers conform to Unicode 3.0 standard. Identifiers may begin with an underscore (connector)
character, although this is not recommended
Operators
Unary Operators
There are three unary operators supported by Visual Basic: +, −, and Not (Unary Plus, Unary Minus, and
Unary Logical Not, respectively). They are defined as follows:
• Unary Plus The value of the operand
• Unary Minus The value of the operand subtracted from zero
• Unary Logical Not Performs logical negation on its operand.
Unary Plus is also the additive operator. However, the operator is "overloaded" to perform a
concatenation function if the operands are discovered to be of type string. For example, the following
code
Dim S As String = "what is "
Debug.WriteLine(S + "this")
writes "what is this" to the Debug window.
Note: Use the & symbol for concatenation because it makes code easier to read.
Unary Minus converts a positive number into a negative one. For instance, this simple math
x = 3 + −1
Debug.WriteLine(x)
writes 2 to the Debug window. However, it's the same thing as 3 minus 1.
The Unary Logical Not is different altogether. It can change a Boolean result (False becomes True or
True becomes False). As mentioned earlier, it can also perform a bitwise comparison on a numeric
expression.
Here are the rules for the Unary Not Boolean expressions:
Unit 3: Programming in Visual Basic .Net 10
Prof Sushant. Sundikar Visual Basic .Net
• If the Expression is False, then the Result is True
• If the Expression is True, then the Result is False
Here's an example:
Dim x As Integer = 5
Dim y As Integer = 1
Dim z As Boolean = True
If Not (x > y = z) Then
Debug.WriteLine("True")
Else
Debug.WriteLine("False")
End If
Normally, the result would be "True" to the debug window, but in the above case truth is Not true. The
Boolean condition inside the parentheses (this entire expression is the operand) is reversed in this case
True is made False.
Arithmetic Operators
The full complement of arithmetic operators is available to Visual Basic .NET.
Operator Description Action/Usage
+ Addition Value = Expression + Expression
− Subtraction Value = Expression -Expression
* Multiplication Value= Expression * Expression
/ and \ Division Value = Expression / \Expression
Mod Modulus (division returns only the
remainder; % in J#, C# C++, etc)
Value = Expression Mod Expression
^ Exponentiation Value = Expression ^ Expression
Assignment Operators
These operators assign values to variables, which are the left operands of an assignment expression.
Theassignment operators come in two forms, simple and compound, as listed in Table B
Table B: Assignment Operators
Operator Description Action/Usage
= Assignment Value = Expression
+= Addition/Concatenation
assignment
Variable += Expression
-= Subtraction assignment Variable −= Expression
*= Multiplication assignment Variable *= Expression
/= and \= Division assignment FloatingPointVariable /= Expression
IntegerVariable \= Expression
^= Exponentiation assignment Variable ^= Expression
Unit 3: Programming in Visual Basic .Net 11
Prof Sushant. Sundikar Visual Basic .Net
&= Concatenation assignment Variable &= Expression
The simple assignment uses the equal sign to assign the operand on the right side to the operand on the
left side. For example, the following code
x = 5
assigns the number 5 to the operand x.
The compound version assigns the result of a numeric operation specified by the operator to the left
operand. The most useful of these compounds is the += operator, which increments the left operand by
the value of the right one and then assigns the result back to the left operand. For example
Dim x as Integer = 5
x += 1
increments the value of x by 1, so the new value of x is 6.
Comparison Operators
The comparison, or relational, operators evaluate an expression and return True or False (Boolean).
• When comparing types, the following behaviors must be noted:
• With Byte, Short, Integer, and Long we compare the numeric (literal) values of the operands.
• With Single or Double we compare the operands of Floating type .
• With Decimals we compare the numeric values of the two operands.
• With Boolean values (True and False) compared for equality, the equals operator (=) will return
• True if both operands are either True or False. The Not Equals (<>) is the reverse.
• With Dates we compare the complete date and time values of the two operands.
• With Chars we compare the Unicode values of the operands.
• With Strings the operators perform either binary or text comparison.
Table C: Comparison Operators Supported in Visual Basic .NET
Operator Description Action/Usage
< Less Than Expr1 < Expr2
<= Less Than or Equal To Expr1 <= Expr2
> Greater Than Expr1 > Expr2
>= Greater Than or Equal To Expr1 >= Expr2
<> Not Equals Expr1 <> Expr2
= Equals Expr1 = Expr2
Unit 3: Programming in Visual Basic .Net 12
Prof Sushant. Sundikar Visual Basic .Net
Concatenation Operator
The concatenation operator, represented by the ampersand (&), combines two string operands and
returns a single string expression. The usage is
Value = operand & operand
Here is an example:
Dim X As String = "1"
Dim Y As String = "23"
Debug.WriteLine(X & Y)
The result of the operation X & Y writes "123" to the debug window.
Logical Operators
Logical operators take Boolean (logical) operands and return the Boolean result of their operations.
Table D: Logical Operators and Their Functions
Operator Function
And (logical And) Returns True if both operands are True otherwise False
Or (logical Or) Returns True even if one of the operands is True returns
False only if both are False
Xor (logical Xor) Returns False if both operands are either True or
False otherwise it returns True
AndAlso Returns True if both operands are True returns False if only
the first operand is True but if the first operand is False,
the second operand is not evaluated and True is returned
OrElse If the first operand is True, the second is not evaluated and
the operator returns True Returns False if both are False
and True if only the second operand is True
For example, in the following code, a logical And operation is performed on two Boolean operands:
Dim catlovesdog As Boolean = False
Dim doglovescat As Boolean = True
Dim weirdromance As Boolean
weirdromance = catlovesdog And doglovescat
Debug.WriteLine(weirdromance)
Conditions upon which Logical Operators Return True or False
If cat loves dog And dog loves cat is love in the air?
True True True
Unit 3: Programming in Visual Basic .Net 13
Prof Sushant. Sundikar Visual Basic .Net
True False False
False True False
False False False
If cat loves dog Or dog loves cat is love in the air?
True True True
True False True
False True True
False False False
If cat loves dog Xor dog loves cat is love in the air?
True True False
True False True
False True True
False False False
If cat loves dog AndAlso dog loves cat is love in the air?
True True True
True False False
False Irrelevant False
If cat loves dog OrElse dog loves cat is love in the air?
True Irrelevant True
False True True
False False False
Bitwise Operators
When your operands are numbers instead of Boolean values, And, Or, and Xor perform bitwise
operations on the operands instead of logical ones. Instead of returning True or False, they return either
a 1 or a 0 depending on the outcome. For example, in the following statement
expression1 And expression2
the operator returns 1 if both operands are 1; but it returns 0 if one of the operands is 0. However, the
following statement
expression1 Or expression2
returns 1 even if only one of the operands is 1. It will return 0 only if both are 0.
You can use the bitwise Not operator with numerical expressions to negate the return value provided by
the operator. The following rules apply to using Not:
• If the bit is 0, then Not makes the bit result 1.
• If the bit is 1, then Not makes the bit result 0.
Control Structures
Programs could be expressed in terms of three core control structures the sequence structure, the
selection or decision structure and the repetition structure. These structures are further explained as
follows:
Unit 3: Programming in Visual Basic .Net 14
Prof Sushant. Sundikar Visual Basic .Net
• The Sequence Structure The default of all .NET languages in which instructions are executed in
sequence, as they are written.
• The Decision Structure This structure uses the If statement to test the verity of a condition.
Multiple choices for tests include the selection structures such as Case. These constructs
interrupt the sequence and transfer control to another location in the program.
• The Repetition Structure This structure also known as the iteration structure comprises actions
that repeatedly execute lines of code until a condition changes, such as a number (until x = y) or
when the end of a list or data structure is reached. They include the recurring While, Do, and
For loops, and they are useful for iterating through lists, arrays, and other data structures.
Conditional Statements
The logical and typical flow of execution of a program is top down. This is known as sequential execution.
However, you can alter execution flow to provide choices that execute one expression or a block over
another with statements that either transfer control to other locations of the method or otherwise
branch or jump from the line that it is currently on to another area in the routine. Conditional
statements could be used to control the sequence of execution and improve the readability and
manageability of program code.
Visual Basic .NET supports several conditional and looping statements for control and flow in programs.
Table below lists the conditional statements that are supported by Visual Basic .NET.
Conditional Action Statement
Decision Making and Switching If. . .Then, Else, Else If, Select Case
Branching GoTo, OnError
If Statement
The If statement is probably the most important conditional of all programming languages and is used in
virtually every one.
The simplest form for this conditional is just plain If . . . Then.
Syntax:
If condition Then [statements]
[Else
[elsestatements]]
End If
Unit 3: Programming in Visual Basic .Net 15
Prof Sushant. Sundikar Visual Basic .Net
The If works as follows: If the test is found to be True, the process continues into the block, and the
code will be executed. If the test is found to be False, then the program jumps over the code directly
after the test and exits the If block. Figure below shows how this works when your code is executed.
Code Snippet:
If X = Y Then 'if condition is true then
Debug.WriteLine ("True") 'execute this statement End If
If…Else Statement
The Else statement is optional, but dependent on If, and it is executed only if the If statement tests
false. The If-Else works as follows: If the test is found to be true, the process will continue into the block,
and the code will be executed. However, if the If test is found to be false, then the execution jumps over
the code directly after the test and enters the Else block.
Syntax:
If condition Then
[statements] [Else
[elsestatements]]
End If
Figure below shows how this works when your code is executed
Unit 3: Programming in Visual Basic .Net 16
Prof Sushant. Sundikar Visual Basic .Net
Nested If
Nested if is If statement inside another If statement. We use Else If to advance the test to additional
elements. It works as follows: If the first If test is found to be false, execution "jumps" over the code
directly after the first test and enters the first Else If block. This next block then proceeds as if it were
the original If test. In other words, this feature affords you additional chances to test a condition.
Figure C shows how the conditional Else If works when your code is executed.
The syntax for the above flowchart is as follows:
If Condition Then
(If Statements)
Else If Condition−n Then
(Else If Statements)
Else
(Else Statements)
End If
The Else statement is also optional and you can nest multiple If statements in the original block as well.
Code Snippet:
If numReceived = DialTone Then
pTone = localDialtone
Unit 3: Programming in Visual Basic .Net 17
Prof Sushant. Sundikar Visual Basic .Net
ElseIf numReceived = TieTone Then
pTone = tieLineDialTone
ElseIf numReceived = OperatorTone Then
TransferToOperator
Else
pTone = fastBusy
End If
Select Case
The Select Case works as follows: An expression is passed to the Select Case function, which proceeds to
test each "case" until it finds a Case value that matches the test expression. The procedure will then
continue into the matching Case block, and its code will be executed. Afterward, the Select Case is
abandoned. Figure below shows how the conditional works when your code is executed.
The syntax is as follows:
Select Case expression_to_test
Case Value1
Statements−for−value1
Case Value2
Statements−for−value2
Unit 3: Programming in Visual Basic .Net 18
Prof Sushant. Sundikar Visual Basic .Net
Case Else
Case−Else−Statements
End Select
Code Snippet:
Select Case Color
Case Gray
Grid.BackColor = Color.FromArgb(128, 128, 128)
Case Red
Grid.BackColor = Color.FromArgb(255, 0, 0)
Case Black
Grid.BackColor = Color.FromArgb(0, 0, 0)
Case Else
Grid.BackColor = Color.DefaultColor
End Select
GoTo
The goto (or GoTo) statement is still used in Visual Basic to help port code and assist with backward
compatibility, though it is not essential to the .NET Framework. Since GoTo was one of the primary
elements of classic BASIC and many other languages, programmers trained in these systems may find it
difficult at first to write code without it.
Here's how it works. The GoTo keyword causes execution to jump from the current line to a label
somewhere else in the block. The syntax is as follows:
GoTo Label
The following code illustrates the "disciplined" usage of GoTo branching.
Start: str = Console.ReadLine()
num = CInt(str)
Goto Line0 'Check num and branch to its corresponding label.
Line0: If num = 1 Then Goto Line1 Else Goto Line2
Line1: Console.WriteLine("This is Line 1 and you typed 1")
Goto Line3
Line2: Console.WriteLine("This is Line 2 and you typed 2")
Goto Line3
Looping Statement
Visual Basic supports the usual loop statements that let you execute one or more lines of code
repetitively while a condition is a certain value, or until it becomes a certain value. The following loops
are supported by Visual Basic .NET.
Unit 3: Programming in Visual Basic .Net 19
Prof Sushant. Sundikar Visual Basic .Net
• Do . . . Loop
• For . . . Next
• For . . . Each . . . Next
• While
DoLoop
The Do . . . Loop command repeats the execution of a block of code for as long as a condition remains
True or until it becomes True. The two variations use the key words While or Until to test the condition:
the former uses While, the latter Until. The syntax for both tests is as follows:
Do [{While | Until} condition ]
statements
Exit Do
statements
Loop
Visual Basic .NET also supports the following variation:
Do
statements
Exit Do
statements
Loop [{While | Until} condition ]
Here is a simple example of the Do . . . Loop:
Do
number = number + 1
Debug.WriteLine("*")
Loop Until number = 50
Now we become more advanced with nesting and other techniques:
Dim incR As Integer
Dim conD As Boolean
Do
Do While incR < 500
incR += 1
Console.WriteLine("Now at: " + CStr(incR))
Unit 3: Programming in Visual Basic .Net 20
Prof Sushant. Sundikar Visual Basic .Net
If incR = 500 Then
conD = True
Console.WriteLine("Now at: " + CStr(incR) + " and Finished")
Exit Do
End If
Loop
Loop Until conD = True
For. . . Next
The For loop is probably the most popular of all Visual Basic loops. The Do loop doesn't need aloop
index, but the For loop does; a loop index counts the number of loop iterations as the loop executes.
Here's the syntax for the For loop—note that you can terminate a For loop at any time with Exit For:
For index = start To end [Step step]
[statements] [Exit For]
[statements] Next [index]
The index variable is originally set to start automatically when the loop begins. Each time through the
loop, index is incremented by step (step is set to a default of 1 if you don't specify a value) and when
index equals end, the loop ends.
Here's how to put this loop to work; in this case, We are displaying "Hello from Visual Basic" four times
(that is, intLoopIndex will hold 0 the first time; 1, the next; followed by 2; and then 3, at which point the
loop terminates):
Module Module1
Sub Main()
Dim intLoopIndex As Integer
For intLoopIndex = 0 To 3
System.Console.WriteLine("Hello from Visual Basic")
Next intLoopIndex
End Sub
End Module
Here's what you see when you run this code:
Hello from Visual Basic
Hello from Visual Basic
Hello from Visual Basic
Hello from Visual Basic
Press any key to continue
Unit 3: Programming in Visual Basic .Net 21
Prof Sushant. Sundikar Visual Basic .Net
For Each…Next Loop
You use the For Each…Next loop to loop over elements in an array or a Visual Basic collection. This loop
is great, because it automatically loops over all the elements in the array or collection—you don't have
to worry about getting the loop indices just right to make sure you get all elements, as you do with a For
loop. Here's the syntax of this loop:
For Each element In group [statements] [Exit For]
[statements] Next [element]
You can get a look at this loop in action with an example like this, in which I'm displaying all the
elements of an array:
Module Module1
Sub Main()
Dim intIDArray(3), intArrayItem As Integer
intIDArray(0) = 0
intIDArray(1) = 1
intIDArray(2) = 2
intIDArray(3) = 3
For Each intArrayItem In intIDArray
System.Console.WriteLine(intArrayItem)
Next intArrayItem
End Sub
End Module
And here's the result of this code:
0
1
2
3
Press any key to continue
While Loop
While loops keep looping while the condition they test remains true, so you use a While loop if you have
a condition that will become false when you want to stop looping. Here's the While loop's syntax (note
that you used to end this loop with Wend in VB6 and before—that's changed to End While now):
While condition [statements] End While
And here's an example putting While to work:
Unit 3: Programming in Visual Basic .Net 22
Prof Sushant. Sundikar Visual Basic .Net
Sub CheckWhile()
Dim intCounter As Integer = 0
Dim intNumber As Integer = 10
While intNumber > 6
intNumber -= 1
intCounter += 1
End While
MsgBox("The loop ran " & intCounter & " times.")
End Sub
And here's what you see when you run this code:
The loop ran 4 times.
Press any key to continue
Declaring Arrays and Dynamic Arrays
Arrays are programming constructs that let you access your data by numeric index. To dimension arrays,
you can use Dim (standard arrays), ReDim (dynamic arrays), Static (arrays that don't change when
between calls to the procedure they're in), Private (arrays private to the form or module they're
declared in), Protected (arrays restricted to a class or classes derived from that class), Public (arrays
global to the whole program).
Syntax:
Dim Array_Name(size) [As Datatype]
Standard Arrays
You usually use the Dim statement to declare a standard array; here are a few examples of standard
array declarations:
Dim Data(30)
Dim Strings(10) As String
Dim TwoDArray(20, 40) As Integer
Dim Bounds(10, 100)
The Data array now has 31 elements, starting from Data(0), which is how you refer to the first element,
up to Data(30).In VB .NET, the lower bound of every array index is 0, and the upper bound elements+1.
The Bounds array has two indices, one of which runs from 0 to 9, and the other of which runs from 0 to
99.
You can also initialize the data in an array if you don't give an array an explicit size; here's the syntax to
use, where we are initializing an array with the values 10, 3, and 2:
Dim Data() = {10, 3, 2}
Unit 3: Programming in Visual Basic .Net 23
Prof Sushant. Sundikar Visual Basic .Net
Dynamic Arrays
Dynamic arrays are array that are declared using a Dim statement with blank parenthesis initially and
are dynamically allocated dimensions using the Redim statement. Dynamic arrays can be dimensioned
or redimensioned as you need them with the ReDim statement . Here's how you use ReDim:
ReDim [Preserve] varname(subscripts)
You use the Preserve keyword to preserve the data in an existing array when you change the size of the
last dimension. The varname argument holds the name of the array to (re)dimension. The subscripts
term specifies the new dimension of the array.
This is one of those topics that is made easier with an example, so here's an example using dynamic
arrays, in which we declare an array, dimension it, and then redimension it:
Dim DynaStrings() As String
ReDim DynaStrings(10)
DynaStrings(0) = "String 0"
'Need more data space!
ReDim DynaStrings(100)
DynaStrings(50) = "String 50"
Understanding Scope
The scope of an element in your code is all the code that can refer to it without qualifying its name. In
other words, an element's scope is its accessibility in your code. As programs go larger, scope will
become more important, and programs will be divided into classes, modules, procedures, and so on.
In VB .NET, where you declare an element determines its scope, and an element can have scope at one of
the following levels:
• Block scope—available only within the code block in which it is declared
• Procedure scope—available only within the procedure in which it is declared
• Module scope—available to all code within the module, class, or structure in which it is declared
• Namespace scope—available to all code in the namespace
Block Scope
If you declare a variable within a block, you can use it only within that block. In the following example,
the scope of the integer variable cube is the block between If and End If, and you can no longer refer to
cube when execution passes out of the block.
If n < 1291 Then
Dim cube As Integer
cube = n ^ 3
End If
Unit 3: Programming in Visual Basic .Net 24
Prof Sushant. Sundikar Visual Basic .Net
Procedure Scope
An element declared within a procedure is not available outside that procedure. Only the procedure
that contains the declaration can use it. Variables at this level are also known as local variables. You
declare them with the Dim Statement (Visual Basic), with or without the Static (Visual Basic) keyword.
Procedure and block scope are closely related. If you declare a variable inside a procedure but outside
any block within that procedure, you can think of the variable as having block scope, where the block is
the entire procedure.
Module Scope
For convenience, the single term module level applies equally to modules, classes, and structures. You
can declare elements at this level by placing the declaration statement outside of any procedure or
block but within the module, class, or structure.
When you make a declaration at the module level, the access level you choose determines the scope.
The namespace that contains the module, class, or structure also affects the scope.
Elements for which you declare Private (Visual Basic) access level are available to every procedure in
that module, but not to any code in a different module. The Dim statement at module level defaults to
Private if you do not use any access level keywords. However, you can make the scope and access level
more obvious by using the Private keyword in the Dim statement.
In the following example, all procedures defined in the module can refer to the string variable strMsg.
When the second procedure is called, it displays the contents of the string variable strMsg in a dialog
box.
' Put the following declaration at module level (not in any
procedure).
Private strMsg As String
' Put the following Sub procedure in the same module.
Sub initializePrivateVariable()
strMsg = "This variable cannot be used outside this module."
End Sub
' Put the following Sub procedure in the same module.
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub
Namespace Scope
If you declare an element at module level using the Friend (Visual Basic) or Public (Visual Basic) keyword,
it becomes available to all procedures throughout the namespace in which the element is declared. With
the following alteration to the preceding example, the string variable strMsg can be referred to by code
anywhere in the namespace of its declaration.
Unit 3: Programming in Visual Basic .Net 25
Prof Sushant. Sundikar Visual Basic .Net
' Include this declaration at module level (not inside any
procedure).
Public strMsg As String
Namespace scope includes nested namespaces. An element available from within a namespace is also
available from within any namespace nested inside that namespace.
If your project does not contain any Namespace Statements, everything in the project is in the same
namespace. In this case, namespace scope can be thought of as project scope. Public elements in a
module, class, or structure are also available to any project that references their project.