2. Unit Covered
Introduction to visual studio
Variables:
Data type conversions, operators and its precedence,
boxing and un-boxing
Flow control in VB
Procedures: subroutines and functions.
Array.
Strings, StringBuilder and Enumerations
Exception handling in VB.NET
3. IDE
Stands for Integrated Development Environment
Visual Studio is a powerful and customizable
programming environment that contains all the tools
you need to build programs quickly and efficiently.
It offers a set of tools that help you
– To write and modify the code for your programs
– Detect and correct errors in your programs.
3
4. IDE cont…
It includes
1. Menu Bar
2. Standard Toolbar
3. Toolbox
4. Forms Designer
5. Output Window
6. Solution Explorer
7. Properties Window
8. Server Explorer 4
6. What is DataType?
In a programming language describes that what type of
data a variable can hold .
When we declare a variable, we have to tell the
compiler about what type of the data the variable can
hold or which data type the variable belongs to.
7. What is Variable?
Variables are used to store data.
Symbolic names given to values stored in memory and
declared with the Dim keyword
Dim stands for Dimension.
constants
– The same as variables, except that constants are
assigned a value that cannot then be altered.
8. How to declare Variable?
Syntax :
Dim VariableName as DataType
VariableName : the variable we declare for hold the
values.
DataType : The type of data that the variable can
hold
Example :
Dim count as Integer
count : is the variable name
Integer : is the data type
9. List of Data types
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)
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;
Double 8 bytes -1.79769313486231E+308 to -4.94065645841247E-
324 for negative values;
4.94065645841247E-324 to .79769313486231E+308
for positive values
Integer 4 bytes -2,147,483,648 to 2,147,483,647
10. List of Data types
Type Storage
size
Value range
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
platform
0 to approximately 2 billion Unicode
characters
User-Defined
Type
(structure)
Sum of the sizes of its members. Each member of the
structure has a range determined by its data type and
independent of the ranges of the other members
11. Access Specifiers
Public: Gives variable public access which means that
there is no restriction on their accessibility
Private: Gives variable private access which means that
they are accessible only within their declaration content
Protected: Protected access gives a variable
accessibility within their own class or a class derived
from that class
Friend: Gives variable friend access which means that
they are accessible within the program that contains
their declaration
12. Access Specifiers
Protected Friend: Gives a variable both protected and
friend access
Static: Makes a variable static which means that the
variable will hold the value even the procedure in
which they are declared ends
Shared: Declares a variable that can be shared across
many instances and which is not associated with a
specific instance of a class or structure
ReadOnly: Makes a variable only to be read and cannot
be written
13. Scope of Variable
Scope : Element's scope is its accessibility in your code.
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
14. Option Statement
The Option statement is used to set a number of
options for the code to prevent syntax and
logical errors.
This statement is normally the first line of the code.
The Option values in Visual Basic are as follows.
– Option Explicit
– Option Strict
– Option Compare
15. Option Explicit
Option Explicit
– Set to On or Off
– Default : On
– This requires to declare all the variables before they
are used.
16. Option Explicit
If Option Explicit mode in ON ,
– have to declare all the variable before you use it in
the program .
If the Option Explicit mode is OFF
– VB.Net automatically create a variable whenever it
sees a variable without proper declaration.
CODE
17. Option Strict
Option Strict
– Set to On or Off.
– Default : off
– Used normally when working with conversions in
code.
– Option Strict is prevents program from automatic
variable conversions, that is implicit data type
conversions .
18. Option Strict
– If Option is on and you assign a value of one type to
a variable of another type Visual Basic will consider
error.
– There is any possibility of data loss, as when you're
trying to assign the value in a variable to a variable
of less precise data storage capacity.
– In that case, you must use explicit conversion.
CODE
19. Option Compare
Default : Binary.
Binary - Optional - compares based on binary
representation - case sensitive
Text - Optional - compares based on text
representation - case insensitive
Code
20. Type Conversion
In Visual Basic, data can be converted in two
ways:
– Implicitly (widening), which means the conversion
is performed automatically,
– Explicitly(narrowing), which means you must
perform the conversion.
21. Implicit Conversions (widening Conversion)
Widening conversion is one where the new data is
always big enough to hold the old datatype’s value.
For example
– Long is big enough to hold any integer.
– Copying an integer value in to long variable is widening
conversion.
22. Example
Module Module1
Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=5
i=d
d=i
Console.WriteLine("Integer value is" & i)
End Sub
End Module
23. Explicit Conversions (Narrowing Conversion)
– When types cannot be implicitly converted you
should convert them explicitly.
– This conversion is also called as cast.
– Explicit conversions are accomplished using CType
function.
i = CType(d, Integer)
or
i=CInt(d)
Code
24. Example
Module Module1
Sub Main()
Dim d As Double
d = 132.31223
Dim i As Integer
i = CType(d, Integer)
'two arguments, type we are converting
'from, to type desired
Console.WriteLine("Integer value is " & i)
Console.ReadKey()
End Sub
End Module
25. CType
Below is the list of conversion functions which we 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.
CObj— Convert to Object type.
CShort— Convert to Short data type.
CSng— Convert to Single data type.
CStr— Convert to String type.
26. Operators
An operator is a symbol used to perform
operation on one or more operands.
Syntax
Oper1=oper2 operator oper3
Example
Sum=a+b
27. Operators
Arithmetic Operators
Operator Use
^ Exponentiation
-
Negation (used to reverse the sign
of the given value, exp -intValue)
* Multiplication
/ Division
Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
29. Difference
Preview
/ operator operator
It is used for Division It is used for Integer Division
e.g.
Dim a As Integer
a = 19 / 5
Result : 4
e.g.
Dim a As Integer
a = 19 5
Result : 3
31. Operators
Logical / Bitwise Operators
Operator Use
Not Negation
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction
32. Operator Precedence
1. Arithmetic operators have the highest precedence and
are arranged this way, from highest precedence to
lowest:
– Exponentiation (^)
– Negation (-) (for example, -intValue reverses the sign of the
value in intValue)
– Multiplication and division (*, /)
– Integer division ()
– Modulus arithmetic (Mod)
– Addition and subtraction (+,-)
2. Concatenation operators:
– String concatenation (+)
– String concatenation (&)
33. Operator Precedence
3. Comparison operators, which all have the same
precedence and are evaluated from left to right
– Equality (=)
– Inequality (<>)
– Less than, greater than (<,>)
– Greater than or equal to (>=)
– Less than or equal to (<=)
4. Logical/Bitwise operators, which have this
precedence order, from highest to lowest:
– Negation-(Not)
– Conjunction-(And,AndAlso)
– Disjunction-(Or, OrElse, Xor)
34. Flow control in VB:
Conditional Statement
Selection statement
Iteration statement
jump statement
35. Conditional Statements
If....Else statement
Syntax
If condition Then
[statements]
Else If condition Then
[statements]
-
-
Else
[statements]
End If
36. Example
Module Module1
Sub Main()
Dim a,b As Integer
If a=b Then
Console.WriteLine(“a equal to b”)
ElseIf a<b Then
Console.WriteLine(“a less than b")
Else
Console.WriteLine(" a greater than b")
End If
Console.ReadKey()
End Sub
End Module
37. Select....Case Statement
It is used to avoid long chains of If….Then….ElseIf
statement.
It compare one specific variable against several
constant expressions then we use select….case
statement.
38. Select Statements
The syntax of the Select Case statement
Select Case test_expression
Case expressionlist-1
statements-1
Case expressionlist-n
statements-n. . .
Case Else
else_statements
End Select
39. Example
Module Module1
Sub Main()
Dim i As Integer
Console.WriteLine("Enter a number between 1 and 4")
i = Val(Console.ReadLine())
Select Case i
Case 1
Console.WriteLine("You entered 1")
Case 2
Console.WriteLine("You entered 2")
Case Else
Console.WriteLine("You entered >2")
End Select
Console.ReadKey()
End Sub
End Module
40. Iteration Statement
For Loop
The For loop in VB .NET needs a loop index which counts
the number of loop iterations as the loop executes.
The syntax for the For loop looks like this:
For index=start to end [Step stepvalue]
[statements]
Next[index]
42. While loop
It runs set of statements as long as the conditions
specified with while loop is true.
The syntax of while loop looks like this:
While condition
[statements]
End While
43. Example
Module Module1 OUTPUT
Sub Main()
Dim d, e As Integer
d = 0
e = 6
While e > 4
e -= 1
d += 1
End While
Console.WriteLine("The Loop run " & e & "times")
End Sub
End Module
44. Do Loop
Do[{while | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
The Do loop can be used to execute a fixed block of
statements indefinite number of times.
The Do loop keeps executing it's statements while or
until the condition is true.
The syntax of Do loop looks like this:
Do
[statements]
[Exit Do]
[statements]
Loop [{while | Until} condition]
45. Example
Module Module1 Output
Sub Main()
Dim str As String
Console.WriteLine("What to do?")
str = Console.ReadLine()
Do Until str = "Cool"
Console.WriteLine("What to do?")
str = Console.ReadLine()
Loop
Console.ReadKey()
End Sub
End Module
46. Example
Write a console application to find out n!.(use for loop)
Write a console application to find out sum of the digits.
– i.e. 1237 : 1+2+3+7 = 13.(using while condition)
Write a program to enter marks of student and
calculate grade of the student.
47. Procedure
They are a series of statements that are executed when
called.
There are two types of procedure in VB .NET:
– Function : Those that return a value.
– Subroutines (Procedure) : Those that do not return
a value.
48. Sub Procedure
Sub procedures are methods which do not return a value.
Each time when the Sub procedure is called the
statements within it are executed until the matching End
Sub is encountered.
Sub Main(), the starting point of the program itself is a
sub procedure.
Sub routine can be created in module and class.
Default access modifier is public.
49. Syntax
[{ Overloads | Overrides | Overridable | NotOverridable |
MustOverride | Shadows | Shared }]
[Access_Specifiers] Sub ProcedureName[(argument list)]
[ statements ]
[ Exit Sub ]
[ statements ]
End Sub
Code
50. Access_Specifiers : Public | Protected | Friend |
Protected Friend | Private
Attribute List - List of attributes for this procedure. You
separate multiple attributes with commas.
– ByVal : Pass by value
– ByRef : Pass by Reference.
Procedure Name: Name of the Procedure
Exit Sub : Explicitly exit a sub procedure.
51. Overloads : it indicates that there are other procedure in the class
with the same name but with different argument.
Overrides :-Specifies that this Sub procedure overrides a procedure
with the same name in a base class.
Overridable : -Specifies that this Sub procedure can be overridden
by a procedure with the same name in a derived class.
NotOverridable:- Specifies that this Sub procedure may not be
overridden in a derived class.
MustOverride:-Specifies that this Sub procedure is not
implemented in class and must be implemented in a derived class.
52. Function
Function is a method which returns a value.
Functions are used to evaluate data, make calculations
or to transform data.
Functions are declared with the Function keyword.
53. Syntax
[{ Overloads | Overrides | Overridable | NotOverridable |
MustOverride | Shadows | Shared }]
[Access_Specifiers] Function Func_name[argument List ]
[ As type ]
[ statements ]
[ Exit Function ]
[statements ]
End Function
54. Type- Data type of the value returned by the Function
procedure can be
– Boolean, Byte, Char, Date, Decimal, Double, Integer,
Long, Object, Short, Single, or String;
Access_Specifiers : Public | Protected | Friend |
Protected Friend | Private
Code
55. Example
The calculate_Amount sub routine takes the quantity
and unit price of product and calculate the total
amount.
The calculate_Amount sub routine takes the quantity
and unit price of product and return total amount.
56. Array
It is a collection of elements of same datatype.
It access using single name and index number.
This is very useful when you are working on several
pieces of data that all have the same variable datatype &
purpose.
57. Type of Array Demo
One dimensional
Dim Array_name(size) as Datatype
e. g. Dim name(20) As String
Dim Array_name() as Datatype=new data type(size){list of
constant separated by comma}
e.g. Dim num() as integer=New integer(5) {1,2,3,4,5}
Multidimensional
e. g. Dim matrix(3,3) As Integer
Dim mat(,) as Integer=New Integer(3,3)
Dim matrix(,) As Integer =New Integer(){{2,2},{0,0},{1,3}}
58. Dynamic Array
You can resize an array using ReDim Keyword.
Syntax
ReDim [Preserve] Array_name(new Size)
If you use ReDim statement then existing content are
erased.
If you want to preserve existing data when reinitializing
an array then you should use the Preserve keyword .
59. Dim Test() as Integer={1,3,5}
'declares an array an initializes it with three members
ReDim Test(25)
'resizes the array and lost existing data.
ReDim Preserve Test(25)
'resizes the array and retains the data in elements 0 to 2
Demo
60. Function In Array
Function Description
GetLength Get length of the array
GetType Get Datatype of an array
First It gets the first element of an array.
Last It gets the last element of an array.
Max It gets the Maximum element of an array.
Min It gets the Minimum element of an array.
61. For Each……Next Loop
This element automatically loops over all the element
in array or collection.
No need to write starting or ending index.
Syntax
For Each element in group
[statement]
[Exit For]
[Statement]
Next [Element]
Example
62. Difference
For For Each
The for loop executes a statement or
a block of statements repeatedly until
a specified expression evaluates to
false.
The for Each statement repeats a
group of embedded statements for
each element in an array or an object
collection.
Need to specify the loop bounds No not need to specify the loop
bounds minimum or maximum
Syntax :
For index=start to end [Step]
[statements]
[statements]
Next[index]
Syntax :
For Each element in group
[statement]
[Exit For]
[Statement]
Next [Element]
63. Difference
While Until
"do while" loops while the test case is
true.
“do until ” loops while the test case is
false.
Syntax :
Do while condition
[statements]
[Exit Do]
[statements]
Loop
Syntax :
Do Until condition
[statements]
[Exit Do]
[statements]
Loop
64. String Function Code
To Do This To USE
Concatenate two strings &, +, String.Concat, String.Join
Compare two strings
StrComp Return Zero if same else 1
String.Compare Return zero if same else 1
String.Equals Return true if same else false
String.CompareTo Return Zero if same else false
Convert strings CStr, String. ToString
Copying strings =, String.Copy
Convert to lowercase or
uppercase
Lcase, Ucase,
String. ToUpper, String. ToLower
65. String Function
To Do This To USE
Create an array of strings from
one string
String.Split
Find length of a string Len, String.Length
Get a substring Mid, String.SubString
Insert a substring String.Insert
Remove text String.Remove
Replace text String.Replace
66. String Function
To Do This To USE
Search strings InStr, String.Chars,
String.IndexOf,
String.LastIndexOf,
Trim leading or trailing spaces
(Remove Unwanted space)
LTrim, RTrim, Trim,
String.Trim,
String.TrimEnd,
String.TrimStart
Work with character codes Asc, Chr
67. Enumeration
Access Modifier : (Optional) Public, Protected, Friend,
Private
[ access modifier ]
Enum enumeration_name [ As data type ]
member list
End Enum
69. Exception
Exceptions : It is a runtime errors that occur when a
program is running and causes the program to abort
without execution.
Such kind of situations can be handled using Exception
Handling.
Exception Handling :
– By placing specific lines of code in the application we
can handle most of the errors that we may encounter
and we can enable the application to continue running.
70. VB .NET supports two ways to handle exceptions,
– Unstructured exception Handling
– using the On Error goto statement
– Structured exception handling
– using Try....Catch.....Finally
71. Unstructured Exception Handling
The On Error GoTo statement enables exception
handling and specifies the location of the exception-
handling code within a procedure.
How the On Error GoTo statement works:
On Error GoTo [ lable | 0 | -1 ] | Resume Next
Code
72. Statement Meaning
On Error GoTo -1 Resets Err object to Nothing, disabling error
handling in the routine
On Error GoTo 0 Resets last exception-handler location to
Nothing, disabling the exception.
On Error GoTo
<labelname>
Sets the specified label as the location of the
exception handler
On Error Resume
Next
Specifies that when an exception occurs,
execution skips over the statement that caused
the problem and goes to the statement
immediately following. Execution continues
from that point.
73. Structured Exception Handling
On Error Goto method of exception handling sets the
internal exception handler in Visual Basic.
It certainly doesn't add any structure to your code,
If your code extends over procedures and blocks, it can
be hard to figure out what exception handler is working
when.
74. Structured exception handling is based on a particular
statement, the Try…Catch…Finally statement, which is
divided into a
– Try block,
– optional Catch blocks,
– and an optional Finally block.
76. The Try block contains code where exceptions can
occur.
The Catch block contains code to handle the exceptions
that occur.
If an exception occurs in the Try block, the code throws
the exception.
It can be caught and handled by the appropriate Catch
statement.
After the rest of the statement finishes, execution is
always passed to the Finally block, if there is one.
Code
77. Exception Object
The Exception object provides information about any
encountered exception.
properties of the Exception object:
– HelpLink : can hold an URL that points the user to
further information about the exception.
– InnerException : It returns an exception object
representing an exception that was already in the
process of being handled when the current
exception was thrown.
78. – Message : It holds a string, which is the text
message that informs the user of the nature of the
error and the best way or ways to address it.
– StackTrace : It holds a stack trace, which you can
use to determine where in the code the error
occurred.
79. Standard Exception
Exception Type Description
Exception Base type for all exceptions
IndexOutOfRangeException Thrown when you try to access an array
index improperly
NullReferenceException Thrown when you try to access a null
reference
InvalidOperationException Thrown when a class is in an invalid
state
ArgumentException Thrown when you pass an invalid
argument to a method
ArithmeticException Thrown for general arithmetic errors
80. Difference
VALUE TYPE REFERENCE TYPE
Value type they are stored on
stack
Reference type they are stored on heap
When passed as value type new
copy is created and passed so
changes to variable does not get
reflected back
When passed as Reference type then
reference of that variable is passed so
changes to variable does get reflected
back
Value type store real data
Reference type store reference to the
data.
Value type consists of primitive
data types, structures,
enumerations.
Reference type consists of class, array,
interface, delegates
Value types derive from
System.ValueType
Reference types derive from
System.Object