unit-3
unit-3
Structure:
3.0 Objectives
3.1 Introduction
3.2 Data Types
3.3 Operators
3.4 Decision Making and Loop Structures
3.5 Error Handling
3.6 Classes and Objects
3.7 Summary
3.8 Questions and Exercises
3.9 Suggested Readings
3.0 Objectives
After studying this unit, you will be able to:
list and explain the data types support by VB .NET
list and explain the operators
write a program using decision making and looping structure
discuss the error handling techniques in VB .NET
3.1 Introduction
In the previous unit we discussed the concept of Visual Studio .NET and
Microsoft Development Environment. Integrated design environment and
integrated debugging environment that helps the program developers to
develop the application in a convenient way. Some basic concepts and
basic skills required to work with the Development Environment. We also
discussed to develop a simple application in VB .NET environment and to
run the application.
In this unit we are going to discuss the data types, operators, decision
making, looping statements, error handling, techniques supported by VB
.NET platform. Also we are introducing the object oriented programming
concepts in discussing on classes and objects
The variant type, Efficient though it often was, had two fatal flaws from the
perspective of those who designed VB.NET. First, in some cases, VB had a
hard time figuring out which type the variant should change to resulting in an
error. Second, the other languages in the .NET universe do not use variants
and the .NET philosophy requires conformity between its various languages
(at least on the fundamental issues, such as variable typing). Therefore, the
variant variable is no longer part of the VB language. It has been banished
in VB.NET.
X = 10 and y = 10.3
Here when the value 10 assigned to the variable x, VB understands that this
is the integer type. But the y value has the fractional part insist to change
the type to floating type so here casting is happening.
x = "11"
y = 10
z=x+y
MsgBox (z)
From this example you will get the answer as 21, but before doing this
calculation the casting process is require converting from string to integer.
This interpretation process delays the processing or execution time of an
application. Thus the VB .NET is not entertaining the usage of variant type.
The easiest and simplest data type is Boolean. It can represent two states
that is, True and False. The default value of the Boolean is False. This type
can be used where you want to toggle between states of True and False or
say On and Off. The syntax for the Boolean data type is:
Dim bool1 As Boolean
Another simple data type is the Integer and its larger size, the Long type.
Before VB.NET, the Integer data type was 16 bits large and the Long data
type was 32 bits large. Now these types are twice as big as they used to be:
Integer is 32 bits large and Long is 64 bits large. If your program needs to
use a 16-bit integer, use the new type Short. So if you're translating pre-
.NET VB code, you need to change any As Integer or Cint commands to As
Short and Cshort, respectively. Similarly, As Long and CLng now must be
changed to As Integer and Cint. In most programming, the Integer is the
most common numeric data type. If your non-fractional number is larger or
smaller than an integer can hold, make it a Long data type.
Dim abc As Integer
Dim xyz As Long
The other major numeric type is called floating point. It has similar small and
large versions called Single and Double, respectively. Use it when your
program requires the precision of using fractions:
Dim fract1 As Single, fract2 As Double
VB.NET also has a new Char type, which is an unsigned 16-bit type that is
used to store Unicode characters. The new Decimal type is a 96-bit signed
integer scaled by a variable power of 10. Table 3.1 listing the data types
available ib VB .NET.
Table 3.1: Data types in VB .NET
Common
Visual
Language Storage
Basic Value Range
Runtime Type Size
Type
Structure
User- (inherits from Sum of Each member of the structure has a range
Defined System. Value the sizes determined by its data type and
Type Type) of its independent of the ranges of the other
(structure) members Members
3.3 Operators
Operators are nothing but the symbols which insist the compiler to execute
or perform specific logical or mathematical operations. VB .NET has huge
number of operators that support to do arithmetic and logical operations. We
are now going to discuss the most commonly used operators.
Arithmetic operators
Comparison operators
Logical/Bitwise operators
Assignment operators
Arithmetic operator
It is a mathematical operation calculated between any two operands. These
operators can be used in expressions to perform sequence of calculations.
Following table 3.2 shows the various arithmetic operations supported by
VB .NET, you can assume here the variable A holds the value 2 and the
variable B holds the value 7.
Table 3.2: arithmetic operators
Operator Description Example
== Two operands values are verified for its equality. (A == B) is not true.
If the condition is yes then the result is true.
Two operands values are verified for its non-
<> equality. If the condition is yes then the result is (A <> B) is true.
True
Verify whether the value of left operand is
> greater than the value of right operand, if yes (A > B) is not true.
then the result is true.
Verify whether the value of left operand is less
< than the value of right operand, if yes then the (A < B) is true.
result is true.
Verify whether the value of left operand is
>= greater than or equal to the value of right (A >= B) is not true.
operand, if yes then the result is true.
Verify whether the value of left operand is lesser
<= than or equal to the value of right operand, if yes (A <= B) is true.
then the result is true.
Apart from these regular operators that are supported by almost all the
languages following are the operators supported by VB .NET.
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assignment Operator
Table 3.5 listing the assignment operators available in VB.NET
Table 3.5: Assignment operators
In the above program a and b are the two integer variables declared
locally. Here, the if constructs followed by the variable declaration
check for the value of a is 100 and the result is a Boolean type. If the
result is True then the control will enter in to one more if construct
called the nested if. If the
nested if boolean condition results True it prints the statement on the
console. If the first construct result or the inner/nested if result is
false then the statement come out from the if construct and prints the
original value of a and b variables.
Select Case
This construct allows a variable to be tested for equality against a list
of values. Each value is called a case, and the variable being
switched on is checked for each select case.
Select [ Case ]
expression [ Case
expressionlist
[ statements
] ] [ Case
Else
[ elsestatements
] ] End Select
Now we will see one example for Do Loop using exit condition. This
program starts the loop by printing the variable “a” with the initial values as
10, and continues until the value of a reaches 20. Here the condition
checking is at the exit level so first time the loop will be executed and
checks for condition to proceed further.
Sub Main()
Dim a As Integer =
10 Do
Console.WriteLine("value of a: {0}",
a) a = a + 1
Loop Until (a = 20)
Console.ReadLine()
End Sub
Output : Value of a:11
-
-
Value of a: 19
For Next
This loop executes for single or group of statements for a specified number
of times, here the loop index counts the number of iterations. This loop can
be terminated at any point of time using Exit For statement.
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
For Each loop is used exclusively for accessing and manipulating all
elements in an array or in VB.Net collection.
For Each element [ As datatype ] In group
[ statements ]
[ Exit For ]
Next [ element ]
You can see the example below, For Each loop statement that reads the
array value one by one and prints the same. This loop continues to work
until it reads entire items from an array.
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7,
9} Dim arrayItem As Integer
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
Output: 1, 2, 5, 7, 9
While End While
It is yet another loop executes single or group of statements until the given
condition is true. Main key point with while loop is that it starts with the
condition of checking the conditional statement, if the condition results as
false the loop statements will be skipped and the statement after the loop
body will be executed.
While condition [
statements ]
[ Exit While ] [
statements ]
End While
Example:
Sub Main()
Dim a As Integer = 10
While a < 20
Console.WriteLine("value of a: {0}",
a) a = a + 1
End While
Console.ReadLine()
End Sub
Output: Value of a:10
-
- Value of a:19
In the above example the variable a is assigned with the value of 10. While
loop starts with the conditional testing of whether the value of a is less than
20. As per this example the condition is True so it starts execute the content
of the loop. It prints the value of a and then the value of a is incremented
with one. When the value of the variable a reaches twenty, then the
condition becomes false and it comes out of the loop and end the process.
With End With
If you take the With End with construct it is not exactly a looping construct. It
does the execution of series of statements that repeatedly refers to a single
structure or object.
With object
[ statements ]
End With
Public Class student
Public Property Name As String
Public Property course As String
Public Property semester As String
End Class
Sub Main()
Dim stud As New student
With stud
.Name = "Mr.X"
.course = "MCA"
.Semester =
"Five" End With
With stud
Console.WriteLine(.Name)
Console.WriteLine(.course)
Console.WriteLine(.semester)
End With
Console.ReadLine()
End Sub
You can observe in the above program group of data is created using the
same property and it is been referred by the With construct.
Nested Loops
As we discussed earlier nested are, building of loop construct inside the
loop. VB .NET supports this concept with all the loops like Do, While For etc.
Below you can find syntaxes pertaining to nested loops.
For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ] For
counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ]
...
Next [ counter2 ]
Next [ counter 1]
While condition1
While condition2
...
End While
End While
3.5 Error Handling
VB .NET supports two types of error handling through which we can avoid
the termination of program during execution. The broad categories are
Unstructured error handling
Structured error handling
Generally error happens during the run time also called as exceptions
generated due to unexpected or abnormal condition during execution of
code.
Here Go To line is used to enable the error handling routine, located at the
starting of the line, it may be either label or number. When the specified line
number or label does not occur in the procedure it raises the compiler error.
To avoid the un expected behavior when no error occur we can place Exit
Sub, Exit property or Exit Function just near the line number or label.
GoTo 0: Disables the enabled error handler that is defined within the current
procedure and resets it to Nothing.
GoTo -1: Disables the enabled exception that is defined within the current
procedure and resets it to Nothing.
Resume Next: Moves the control of execution to the statement that follows
immediately after the statement that caused the run-time error to occur, and
continues the execution from this point forward. This is the preferred form to
use to access objects, rather than using the On Error GoTo statement.
Below you can find the situation where and how these error techniques can
be handled.
‘Generate an error if the user cancels.:
dlgOpenFile.CancelError = True
‘Ignore errors for now :
On Error Resume Next
‘Present the dialog :
dlgOpenFile.ShowOpen
‘See if there was an error:
If Err.Number = cdlCancel Then
‘The user canceled. Do
nothing: Exit Sub
‘Unknown error. Take more action.
ElseIf Err.Number <> 0 Then
End If
‘Resume normal error
handling: On Error GoTo 0
The definition of class will gives you a blueprint of a data type. Actually
whenever you define a class doesn’t mean that you are defining a data. It
indicates the content of the object of the class and various operations that
can be performed unit this objects. The data members and the functions to
perform operations on these data are the members of the class. Objects are
nothing but the instance of a class. You can see below the class construct
that can be defined in VB .NET language. It starts with the key word called
class and followed by the name of the class. Inside the body list of members
will be declared and ends with the End Class statement.
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable
] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
attribute list: attributes list of the table all the square brackets in the syntax
indicates, it is optional.
Access modifier: Has three types of access specifier like private, protected
and public defines the scope of the class member.
Shadows: Declared and hidden as overload member in the name class.
Must Inherit: Indicates you cannot create object for this class only this class
can be used for inheritance.
Partial: specify the fractional definition of the class.
Inherits: Indicates which class is inherited.
Implements: used to specify the interface of the class inherited from
To start with the new application development you need to click on file from
the menu bar and select the new project. The new project dialog box will
appear as depicted in figure 2.9.
Fig. 2.9: new project dialog window
Visual Programming
You can see five templates before you; here we are going to select the
Windows Forms application since we are developing windows application.
By default you get the name as windowsApplication1 you can also change
the name according to your application nature and select ok to continue. As
we discussed already the solution explorer will list all the forms and project
of the current application. Now you will get the window with the new form as
appear in the figure 2.10. Here the application title is specified as My First
Program and the project name is given as My project1. Under that you can
see a form1 is listed through which we are going to develop our application
you can rename this form by changing the name of the form through the
property window say “Multiplication”.
Now we can design our first application to multiply two numbers when you
click on the button which is available on the form. First we will see how to
add a button in the form, towards the left hand side in the new form window,
the Toolbox window appears under the common control you can see the
control called Button. To add this button to the form either you can drag and
drop the control to the form or select and double click on the form to put the
control in the form change its default name to multiply using the property
window. These dragged and dropped controls can be resized later and can
located anywhere in the form according to developer wish. For this
application we also need three more TextBox controls, the same you can
bring these TexBox controls to the form. Two TextBox controls are to accept
input and one more to display the calculated result.
Visual Programming
Now we will see how to add the coding portion in the application. Here the
event decided for calculating or multiplying two numbers are “Click on
button”. To go to the code window either we can do double click on the
button control or through solution explorer you can reach the code window.
If you double click you can see the below procedure appears automatically.
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
End Sub
Within this block we need to type the coding or the business logic to do the
calculation.
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles
Button1.Click Dim a, b, c as single
a= TextBox1.Text
b=TextBox2.Text
c=a*b
TextBox3.Text=c
End Sub
Running VB .NET application
Once the coding part is over we need to execute or run the program to see
the output. We can run the VB. NET application in two ways either by
pressing the F5 button or by selecting the run option from the toolbar. For
the above specified coding the result will appear as shown in figure 2.11.
3.7 Summary
Each variable in VB .NET has a specific type that defines the size and layout of the variable
in memory.
Among all the data types Boolean data type is considered as a simple one.
Operators are the symbols which insist the compiler to execute or perform specific logical or
mathematical operations.
AddressOf, Await, GetType and Function Expression are the special data types supported in
VB .NET
VB .NET supports two types of error handling through which we can avoid the termination of
program during execution are structured and unstructured error handling techniques.
Class is defined as “A container for data and code. The data within the class can be
accessed with properties. The code is referred to as methods”.
Object is defined as “An instance of a class in memory. An instance is created using a Dim
statement and the New keyword”
3.8 Questions and Exercises