Wednesday, 11 January 2012

Classes


One of the major problems in the earlier approach was also the data and the functions working upon the data being separate. This leads to the necessity of checking the type of data before operating upon the data. The first rule of the object-oriented paradigm says that if the data and the functions acting upon the data can go together let them be together. We can define this unit, which contains the data and its functions together as a class. A class can also be defined as a programmatic representation of an entity and the behavior of that entity can be represented by the functions in the class. In our earlier case study the employee, can be represented as a class. A class will contain its data into various variables, which would be termed as data members and the behavior of
the class, which will be encapsulated, as functions will be termed as member functions.

Object Oriented Programming


   Now with the major shortcomings of procedural programming let us look at how a different approach would help us. As mentioned earlier it is necessary to concentrate more upon the entities in the application and not only upon the tasks done by the application.
   Based upon this bottom line we have a certain set of rules defined as object oriented paradigm. If a programming language satisfies these rules i.e. provides certain features or keywords to implement these rules it would be qualified as an object oriented programming language.
   Lets discuss the major conventions for object-oriented programming.

Concept of Procedural Programming


   The whole core of procedural programming lies in deriving a straightforward sequential step-by-step guide to do a particular task. Let us understand this by analyzing a case study.
   Lets take up a classic Payroll application that deals with various types of specifications for different employees. Lets say that this application is developed in one of the best procedural languages – C.
    So, the “Employee” in the application will be represented by a structure, which will contain all the Employee attributes as data members of the structure. Assume that the application deals with three types of employees – Clerk, Manager and Marketing executive. All the employees do have some common
attributes and certain specific allowances (lets not talk of deductions!). The clerk gets medical allowance, the executive gets the traveling allowance and the manager gets house rent allowance and dearness allowance. Our Employee structure might look something like this:

struct Employee
{
int Id;
char Name[25];
char *Address;
char Designation[20];
double Basic;
float Med_Allow;
float Tra_Allow;
float HRA;
float DA;
}

The application would have functions, which would act upon the data, and do the necessary functionalities. So there would be at least following functions apart from others:

void AddDetails() ; // To add details of the
// employee to the structure
void PrintDetails() ; // To print the details of a
// particular Employee
double CalcSalary(); // To calculate the salary of a
// employee

This also could have been done having three different structures one for each Employee type but this would increase the overhead in programming in the functions and there would be a requirement of declaring three different arrays; one to store all clerk variables, one for manager variables and one for executive.
So let us have a common structure, which would suite all the employee types.
   If we try to figure out the central algorithm of every function it would be quite monotonous wherein every function would have a strict type inspection routine to check the type of Employee every time. Because the functionalities differ for every type of Employee.

void CalcSalary ()
{
switch(EMP_TYPE)
{
case CLERK:
// All the CLERK specific calculations
case MANAGER:
// All the MANAGER specific calculations
case EXECUTIVE:
// All the EXECUTIVE specific calculations
}
}

   This kind of type inspection will be featuring in every function, which would be dependant upon the type of the Employee.
  Now, if we have to add a new Employee type to this application, which has its own specification about, the allowances received try to figure out the changes that we will have to do in the current case study. Not only will the Employee structure have to be modified but also even the functions have to be changed in order to accommodate the new Employee type. So just as we are currently having a case statement to correspond to one employee type, we will have to introduce one more case statement corresponding to the new employee type. In addition, while calculating the salary we might introduce some local variables in the function to do the necessary calculations. There is a probability that the new additions may lead to certain bugs being introduced in the current “working” code. So let us list down the various problems we would face in this application:
Maintenance: -- If the application has to support some change in the existing business logic for a particular employee type there might be more problems introduced since it is the same function that would be called for the different employee types.
Enhancement: -- When the application has to be enhanced further to add a new type of employee there would be changes made in all the functions, which depend upon the type of employee. Hence enhancing an application further  would be quite hectic. Why only new type of employee? Even if have to add a little more functionality to an existing function it would prove quite cryptic.
Extensibility: -- The current design of the application does not allow us to have extensibility easily. Therefore, if we have to add more functions, which would do certain tasks for all the employee types or maybe for some of the type of employees; the new function also will have a strict type inspection routine to
check for the type of employee.
Storage: -- A small but significant problem. Whenever we have the data saved in a persistent storage i.e. having the data into files on the hard disk we will have to take care of saving the data along with the appropriate type of the employee. Also, while reading the data from the file its necessary to read the type first and then accordingly initialize the members in the structure.
   If we try to look for the core problem in the application design which can be qualified as a cause for all the problems discussed above it definitely would be an attempt to design a common algorithm to suit all the types of employees. It would definitely prove helpful if rather than concentrating on the procedures we concentrate more upon the entities in the application.

Object Oriented Programming Concepts


There are various approaches to solve a problem. Moreover, these approaches are to a great extent dependant upon how each one of us tries to analyze and solve the problem.
We have a very simple assignment:
Lets say we want to calculate a distance formula for traveling from one place to another. The distance formula has to include all the attributes of the journey. So let us see what data do we have-

Variables:
Location: Have to go from one city to another (both the cities can be anywhere in the world).
Modes of travel: Car/Bus/Train
Date constraints: Departure/Arrival Date.
Time Preference: Morning/Afternoon /Evening
Distance: Break Journey
Travel Cost. Etc
Now, we have termed these data items as “variables” because their value would be changing based upon the various choices made.
Even for such a trivial problem, there are being so many options/constraints, there are so many approaches to arrive at a decision. On similar lines, given a problem and basic resources (which also act as constraints), various algorithms can do the task programmatically. An algorithm is nothing but the thought process/approach involved.
A good approach should
• Be generic so that it works well with all possible combinations of inputs.
• Flexible / adaptable to absorb new inputs. (New destination, routes, rates, timings or even new mode of travel - say space travel)
• Give solutions in the desired timeframe.
• Make best use of resources available. (Optimize the solution)
• Cost effective.
• Simple enough.
   Primitively, there was a very straightforward manner to write applications. Straightforward in the sense that the various tasks in the application would be identified and would be automated. This approach did work for many scenarios but when it came to the robustness or maintenance of the application, this approach proved to be insufficient.
   In this section we will first discuss what was the procedural approach and how the design of an application be made using this approach. By trying to figure out the negative points in the approach we will then appreciate the advantages of object oriented programming by discussing it as a solution to overcome the
shortcomings of procedural programming.

Arrays


Till now we have been using variable to store values. We might come across a situation
when we might need to store multiple values of similar type. Such as names of 100
students in a school. One way to do it is to declare 100 variables and store all the names.
A much more simple and efficient way of storing these variable is using Arrays. An
Array is a memory location that is used to store multiple values.
All the values in an array are of the same type, such as Integer or String and are
referenced by their index or subscript number, which is the order in which these values
are stored in the array. These values are called the elements of the array.
The number of elements that an array contains is called the length of the array.
In VB.Net all arrays are inherited from the System.Array Class.
Arrays can be single or multidimensional. You can determine the dimensions of an array
by the number of subscripts that are used to identify the position of any array element.
A single dimensional array is identified by only a single subscript and an element in a
two-dimensional array is identified by two subscripts.
The dimension has to be declared before using them in a program. The array declaration
comprises the name of the array and the number of elements the array can contain.
The Syntax of single dimension array is as follows.
Dim ArrayName (number of elements) as Element Data type.
e.g.
Dim studentname(10) as string
Or
Dim studentname() as string = new string(10)
You can assign the values at runtime or even at the design time.
Design time declaration:
Studentname(0)=”Rohan”
Studentname(1)=”Mohan”
…..
Studentname(10)=”Nitin”
All arrays starts with the index of 0 i.e. All arrays are Zero Based and there is no
provision of an option Base Statement where in you can specify the Lower Bound . This
implies that above array can store 11 elements. Here 0, is the starting index or the lower
bound of the array. The lower bound is fixed for all the arrays.
Example 1.
We will create a VB.Net application that will accept the names of students in an single
dimension array and display it back.
Add a textbox and set the name property to txtnames. Set the multilane property of the
text box to true.
Put a button and write the following in the onclick event.
txtnames.Text = ""
Dim value, count As Integer
'Accept how many students names to enter
value = CInt(InputBox("Enter the number of students name to enter:"))
Dim arrnames(value) As String
Dim cnt As Integer
For cnt = 0 To value
arrnames(cnt) = InputBox("Enter the name of student " & cnt + 1 & ":",
"Student Name")
Next
'Display the entered value to the text box
For cnt = 0 To value
If txtnames.Text = "" Then
txtnames.Text = arrnames(cnt) & vbCrLf ' for carriage returns
Else
txtnames.Text = txtnames.Text & arrnames(cnt) & vbCrLf
End If
Next
Above example will accept number of names to be entered and will add the names in a
loop and then redisplay it in a text box.
The Syntax for multi-dimension arrays is as follows:
Previously we saw how we can store multiple names of students. But, if we want to store
related data of students like first name, middle name, last name. In such situations you
can use multi dimension arrays, such as two-or-three dimension arrays.
Dim ArrayName (number of 1st element, number of 2nd element,….) as element data
type.
Or
Simpler form would be
Dim ArrayName( number of rows, number of columns) as element data type of two
dimension.
e.g.
Dim studentdetails(10,2) as string
Index positions of array elements.
0,0 0,1
1,0 1,1
2,0 2,1
3,0 3,1

10,0 10,1
studentdetails(0,0) = “Manoj”
studentdetails(0,1) = “Malik”
To display “Malik” we need to use the index position of the array and say ,
Studentdetails(0,1).
Example 2.
We will create a VB.Net application, which will accept Student Name, Address and city
name and display it in the text box in a formatted way.
As in the earlier example we will create a text box , change its name and its multi line
property to true.
Change the text box to txtsummary.
Add a button and write the below code in that.
Dim arrsummary(3, 3) As String
Dim i, j As Integer
'As we wanted just 3 columns we have set it to 2, else if u want to be
two only then while declaring the array make it (2,2) as the lower
index is 0.
For i = 0 To 2
For j = 0 To 2
arrsummary(i, j) = InputBox("Enter the value for " & i & " row _
and " & j & " column ", "Summary")
Next
Next
'Display the values in the summary array.
For i = 0 To 2
For j = 0 To 2
If txtsummary.Text = "" Then
txtsummary.Text = arrsummary(i, j)
Else
txtsummary.Text = txtsummary.Text & "-" & arrsummary(i, j)
End If
Next
txtsummary.Text = txtsummary.Text & vbCrLf
Next
Mohan #2/b,4th lane Kanpur
Mike 8th block csd NY
Lim Chou Lane Hong Kong
Dynamic Arrays.
Till now what we read were about fixed arrays. Let us see how we can manipulate the
size of an array at run time.
Many times we feel that the size of array in not enough or too much then required. As we
know that array will allocate memory location when its declared, so to release or add
more we need to change the dimension of the array which has been pre-declared.
We can create a dynamic array by not specifying the size of the array at the time of array
declaration.
Syntax:
Dim student_names() as string
In the above syntax you will see that number of elements are not mentioned. Now to redeclare
the elements we make use of ReDim for an array to change its dimension.
e.g.
Dim student_names() as string
ReDim student_names(10)
ReDim can also change the size of multi-dimensional arrays.
You can change the number of dimensions in an array, but you cannot make a multidimensional
array to a single dimension or lesser than the original dimension.
e.g.
Dim student_details(10,15) as string 'Declaring the array
ReDim student_details(10,25) 'Resizing the array
This statement does not change the data type of the array element or initialize the new
values for the array elements.
This statement can be used at the procedure level only not at the class level or module
level.
ReDim statements reinitializes the value of arrays with the respective data type declared
by the array.
If u have initialized the array to a some values it will be lost during the time of resizing
and the default values will be restored in those elements.
E.g.
'Declaring the array and initializing the value for the array
dim students_names() as string = {“Rahul”}
'This will display the value Rahul
msgbox(students_names(0))
Now resizing the array.
ReDim students_names(10)
'This will give a fixed size to 10 elements
msgbox(students_names(0))
This will display a blank value, as during the resizing the values of the array are
reinitialized to default value of string which is blank.
Now to avoid such problems we will make use of a keyword called Preserve while
resizing the array to new value.
Using the above example , we will make changes in the declaration.
ReDim students_names(10) 'The old declaration
ReDim Preserve students_names(10)
Students_names(1) = “Alex”
Students_names(2) = “Michael”
Msgbox(students_names(0))
This will display the value as ‘Rahul’ which we had initialized before resizing it. So
Preserve will restore all the initialized value of elements declared in an array.
If the array is an two or more dimensional array , you can only change the size of the last
dimension by using preserve keyword.
Dim student_details(10,20) as string
ReDim preserve student_details(15,25)
This will raise error because we are trying to change the first dimension also. So u can
only change the last dimension in case of multi-dimensional array.
Few Important methods in arrays.
Ubound() and Lbound().
Ubound is to get the upper limit of an array.
Lbound is to get the lower limit of an array by default lower limit is 0.
e.g.
Dim weeks() As String = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"}
Dim upper As Integer
Dim lower As Integer
upper = UBound(weeks)
lower = LBound(weeks)
MsgBox(upper.ToString & " - " & lower.ToString)
You will get 6 – 0 as the answer.
If you count the number of elements initialized elements its seven, but all arrays starts
with lower bound as 0. So from 0 – 6 is equal to 7 elements.
This works for single dimension , but for multi-dimensions,
We make use of the following:
Getupperbound(), getlowerbound() these functions are methods of the array class.
You can use it with single dimension also but best for multi-dimensional arrays.
Syntax : arrayname.getupperbound/getlowerbound(dimension)
Dimension refers to the which upper/lower bound should be found, 0 for first, 1 for
second and so on.
example.
Dim student_details(10,20,15)
Dim upperlimit as integer
upperlimit = student_details.getupperbound(0)
' This will return 10 for the 1st row element
upperlimit = student_details.getupperbound(1)
' This will return 20 for the 2nd row of element
For all getlowerbound(dimension) it will return 0 as the base lower bound is zero in .NET

Control Statements


VB.Net has statements such as If .. Then ..else and Select …. Case, which help you to
conditionally execute program.
VB.Net provides you with various looping statements, such as Do… Loop, While…. End
While, and For… Next.
1. The If….Then….Else…End if Statement
Consider a student marks and grade evaluation. For Marks above 75 the grade is ‘A’ and
for below 75 is ‘B’. In this situation when you need to execute some code based on some
condition, you can make use of, If…then…else…end if.
The Cultural syntax normally used is as follows:
If condition Then
Executable statements when the condition is True
Else
Executable statements when the Condition is False
End If
OR using Elseif for Advanced Decision making
If condition Then
Executable statements
ElseIf condition Then
Executable statements
End If
Single if can have multiple else with conditions, as mentioned above in elseif format and
finally a single End If for the main If condition.
Nesting IF…Then Constructs
If condition Then
If condition2 Then
Executable statements when the condition2 is TRUE
Else
Executable Statements
End if
Else
Executable statements
End If
One important thing to keep in mind when nesting IF…Then constructs is that you must have corresponding End If statement for
every IF ..Then statement, unless the If then statement executes only one statement and that statement appears on the same line as
If…Then
2. The Select…Case Statement(Evaluating an Expression for Multiple Values)
The Select…Case Statement is similar to If…Else…End if. The only difference between
two is that If and elseif can evaluate different expressions in each statement, but the
Select statement can evaluate only one expression.
The drawback of IF...Then construct is that it isn’t capable of handling a decision
situation without a lot of extra work. One such situation is when you have to perform
different actions based on numerous possible values of an expression, not just True or
False. For instance performing actions based on Students Marks.
If intmarks >35 Then
…….
Elseif intmarks >50 then
……
Elseif intmarks>65 then
…..
Elseif intmarks>75 then

Else
….
End If
As you see the structure can be a bit hard to read and if the conditions increase you may
end up writing a confusing and an unreadable piece of Code
The Select uses the result of an expression to execute different set of statements.
The syntax for the Select…Case Statement is as follows:
Select Case [expression]
Case [expression list]
Executable statements.
Case Else
Executable statements.
Exit Select - to exit from the select
End Select
Note: Case Else is used to define the code that executes only when the expression doesn’t
evaluate to any of the values in Case Statements .Use of Case Else is optional
Lets see the same example as above but this time with Select Case
Select Case intmarks
Case Is >35
Executable statements
Case Is >50
Executable statements
Case Is>65
Executable statements
Case Is >75
Executable statements
Case Else
Executable statements
End Select
Evaluating More than one possible Value in a Case Statement
Select Case helps you to use some more advanced expression comparisons. Like,you can
specify multiple comparisons in a Single Case statement by just using comma. Lets see
how it does
Select Case strColor
Case Is=”Red”,”Blue”,”Magenta”
‘Color is a Dark Shade
Case Is =”Cream”,”white”
‘Color is a Cool Shade
End Select
Another comparison expression used is keyword To, Visual Basic.NET evaluates the
expression and finds out whether it is in the range mentioned and if yes the Statement is
executed. Please note that when using To, you can’t include Is = as you can with the
simple expression
Select Case intmarks
Case 1 to 35
‘Executable statements
Case 36 to 50
‘Executable Statements
End Select
3. For…Next Statement
The For…Next Statements are used repeat a set of statements for specific number of
times.
The syntax for the For…Next Statements is as follows:
For counter = <start value> to <end value> [Step Value]
Executable Statements
Exit For
Next [counter]
Counter is any numeric value.
Start value is the initial value of the counter.
End value is the final value of the counter.
Step Value is the value by which the counter is incremented. It can be positive or
negative. The default value is 1.
Exit For is used to exit the For…Next loop at any time. When Exit for is encountered
,the execution jumps to the statement following Next
Next is the statement the marks the end of the For statement. As soon as the program
encounters the Next statement, the step value is added to the counter and the next
iteration of the loop takes place.
Dim intctr as Integer
For intctr=1 to 100
Debug.WriteLine(intctr)
Next intctr
This routine starts a loop with a For statement after a variable intctr is declared. This loop
initializes intctr to 1 and then prints 1 through 100 to the output window. It prints in steps
of 1 as Step has been omitted here, so the default is 1
Example of use of STEP in For....Loop.
Let us write a table of 2 using step in for loop.
Add a label with name it as lbtables and make it bit bigger on the screen.
Dim j = 1
For i = 2 To 20 Step 2
Me.lbtables.Text = Me.lbtables.Text & "2 X " & j.ToString & " = " &
i.ToString & vbCrLf
j = j + 1
Next
Output:
2 X 1 = 2
..
..
..
..
..

2 X 10 = 20
An Example of Nested For loop.
Let us write a small code to display a structure of stars ‘*’ in triangle format.
*
* *
* * *
* * * *
* * * * *
* * * * * *
Let us have a label with name stars. Increase the height of the label to get a clear view of
the image.
Dim star As String
Dim i, j As Integer
For i = 0 To 5 ' First loop to count the rows
For j = 0 To i ' Second loop to count the columns
star = star & " * "
Next
Me.stars.Text = Me.stars.Text & star & vbCrLf ' To print *
star = ""
Next
4. For Each…Next Statement
The For Each…Next Statement is used to repeat a set of statements for each element in
an array or collection.
The For Each…Next statement is executed if there is at least one item in an array of
collection.
The Loop repeats of each element in an array or collection.
The syntax for the For Each…Next statement as follows:
For Each Component In Set
Executable statements
Next
Component is the variable used to refer to the elements of an array or a collection.
Set refers to an array or any collection object. e.g.
Dim weeks() As String = {"Monday", "Tuesday", "Wednesday", "Thursday",_
"Friday", "Saturday", "Sunday"}
Dim eachday As String
For Each eachday In weeks
MsgBox(eachday)
Next
An example for using for each element in a collection of string into a single string
element.
Each element of array which is of type string is read from the collection and stored into
the single string type object.
5. While…End Statement
The While…End Statement is used to repeat set of executable statements as long as the
condition is true.
The syntax for the While…End statement is as follows:
While Condition
Executable Statements
End While
In this if the condition is satisfied then the statements are executed. Else it will not
enter the While condition at all.
6. Do...Loop Statement
The Do…Loop Statement is similar to While…End. Here we have two types of
formatting the loop.
a) Do While / Until Condition Executable Statements Loop
b) Do Executable Statements Loop While/Until Condition
The Difference is in a) The loop will be executed if the condition is satisfied, but in b)
The Loop will be executed at least once even if the condition does not satisfy.
Do While Expression
[Statements]
Loop
Do Until Expression
[Statements]
Loop
Note: For VB programmers While Wend is not supported it is While… End now
A Complete Example with set of control statements.
We will create a VB.Net application, which will accept students name and its grade.
Depending up the type of grade it will add remarks.
txtsummary.Text = ""
Dim value, ctr As Integer
'Accept a number from the user
value = CInt(InputBox("Enter the number of students"))
'Check if the validity of the number
If value <= 0 Then
MsgBox("Enter details of at least one student", "Error")
End If
Dim arrName(value) As String
Dim sGrade As String
Dim arrRemarks(value) As String
While ctr < value
'Accept the name of the students
arrName(ctr) = InputBox("Enter the name of the Student"_
& ctr + 1, "Enter Details")
'Accept the grade of the Student
sGrade = InputBox("Enter the grade of the student" &
"(_A/B/C/D/F)", "Grade Details")
' Assign remarks to students
Select Case UCase(sGrade)
Case "A"
arrRemarks(ctr) = "Excellent"
Case "B"
arrRemarks(ctr) = "Good"
Case "C"
arrRemarks(ctr) = "Fair"
Case "D"
arrRemarks(ctr) = "Poor"
Case "F"
arrRemarks(ctr) = "Fail"
Case Else
MsgBox("Incorrect value entered ", _
MsgBoxStyle.Critical)
Exit Sub ' To come out of the program
End Select
ctr = ctr + 1
End While
' Display the summary in the text box
For ctr = 0 To value - 1
If txtsummary.Text = "" Then
If LCase(arrRemarks(ctr)) = "fail" Then
txtsummary.Text = arrName(ctr) & " has failed _
in exams" & vbCrLf
Else
txtsummary.Text = arrName(ctr) & "'s performance is_
" & arrRemarks(ctr) & vbCrLf
End If
Else
If LCase(arrRemarks(ctr)) = "fail" Then
txtsummary.Text = txtsummary.Text & arrName(ctr) &_
" has failed in exams" & vbCrLf
Else
txtsummary.Text = txtsummary.Text & arrName(ctr) &_
"'s performance is " & arrRemarks(ctr) &_ vbCrLf
End If
End If
Next

Tuesday, 10 January 2012

Features of VB.NET

Option Explicit and Option Strict
Option Explicit and Option Strict are compiler options that can be globally assigned to a project and are interpreted at compile time. Setting these options enables programmers to resolve some of the errors (e.g. typological errors) at compile time and thus prevent runtime errors.
Option Explicit
Option Explicit was a feature of VB 6.0 and it has been made a part of .NET environment too. This option can be used only at the module level. When this option is turned on, it forces explicit declaration of variables in that module. This option can be turned "On" or "Off". When it is not specified, by default, it is set to "Off".
Syntax: Option Explicit [On / Off]
When it is set to "On", it checks for any undeclared variables in the module at compile
time. If any undeclared variable is found, it generates a compile time error since the
compiler would not recognize the type of the undeclared variable. When it is set to "On",
variables can be declared using Dim, Public, Private or ReDim statements. Setting this
option to "On" helps programmers do away with any typological errors in the code.
When it is set to "Off", all undeclared variables are considered to be of type Object.
It is preferable to set this option to "On".
Option Strict
Visual Basic language in general does not require explicit syntax to be used when
performing operations that might not be optimally efficient (e.g. late binding) or that
might fail at run time (e.g. narrowing conversions). This permissive semantics often
prevents detection of coding errors and also affects the performance of the application.
VB.NET enables a programmer to enforce strict semantics by setting this option to "On".
When used, this option should appear before any other code. This option can be set to
"On" or "Off". If this statement is not specified, by default, it is set to "Off".
Syntax: Option Strict [On / Off]
When it is set to "On", it disallows any narrowing conversions to occur without an
explicit cast operator, late binding and does not let the programmer omit "As" clause in
the declaration statement. Since setting it to "On" requires explicit conversion, it also
requires that the compiler be able to determine the type of each variable. Thus it is
implied that Option Strict also means Option Explicit.
Visual Basic .NET allows implicit conversions of any data type to any other data type.
However, data loss can occur if the value of one data type is converted to a data type with
less precision or a smaller capacity. Setting this option to "On" ensures compile-time
notification of these types of conversions so they may be avoided.
Explicit conversions happen faster than the implicit conversions performed by the
system. In case of implicit conversions, the system has to identify the types involved in
the conversion and then obtain the correct handler to perform the conversion. In case of
explicit conversions, processing time gets reduced since the type of conversion is
explicitly mentioned.
From programmer point of view, explicit conversion may seem to be a burden since it
slows the development of a program by forcing the programmer to explicitly define each
conversion that needs to occur.
It is always recommended that you set Option Strict to "On" and use explicit conversions.
ByVal is Default
When implementing functions/procedures we often need to pass information. This
information can be passed to the called function/procedure through parameters.
Parameters can be passed by value or by reference.
When ByVal keyword is used, it causes the parameter to be passed by value. In this case,
a copy of the original parameter is passed to the called module. Thus any changes made
to the copy of the parameter do not affect the original value of the parameter.
When ByRef keyword is used, it sends a reference (pointer) to the original value to the
called module rather than its copy. Thus any changes made to the parameter in the
function/procedure will cause the original value to be modified.
With ByRef you are exposing a variable to modification which can lead to an unexpected
behavior. If that procedure calls another procedure and passes the same parameter ByRef,
the chances of unintentionally changing the original variable are increased.
In VB.NET, every parameter, by default, is passed by value if nothing is explicitly
specified. Thus it protects arguments against modification.
Example:
Public Class SampleClass
Sub Proc(ByVal a As Integer, b As Integer, ByRef c As Integer)
a = a + 2
b = b + 3
c = c + 4
End Sub
End Class
Sub Main()
Dim num1, num2, num3 As Integer
Dim Obj As New SampleClass()
num1 = 2
num2 = 3
num3 = 4
Obj.Proc(num1, num2, num3)
System.Console.WriteLine(num1)
System.Console.WriteLine(num2)
System.Console.WriteLine(num3)
End Sub
Explanation:
In the class SampleClass, there is one procedure Proc that takes three integers as
arguments. In Main(), a variable of type SampleClass is defined and three other integer
variables num1,num2,num3 are declared and given some initial values. The procedure is
then called passing these three variables as arguments. First variable num1 is passed by
value, second variable num2 is also passed by value since nothing is specified explicitly
and the last variable num3 is passed by reference since it is explicitly mentioned.
After calling the procedure, when the values of the three variables are checked, you will
notice that num1 and num2 retain their original values since they are passed by value
whereas the value of num3 changes to 8 since it was passed by reference.
Sub and Functions with Parenthesis
In VB.NET, both functions and procedures require parentheses around the parameter list,
even if it is empty.
Example:
Consider the following code that contains two functions and one procedure. The first
function named "HelloWorld" accepts no argument and returns "Hello World". The
second function named "HelloName" accepts an argument and appends that argument to
the string "Hello World" and finally returns the appended string. The procedure named
"Hello" displays the string "Hello World" on the console.
Public Class SampleClass
Function HelloWorld( ) As String
Helloworld = "Hello World"
End Function
Function HelloName(ByVal name As String) As String
HelloName = "Hello " & name
End Function
Sub Hello()
System.Console.WriteLine("Hello World")
End Sub
End Class
Sub Main()
Dim Obj As New SampleClass()
Dim str1 As String
Dim str2 As String
str1 = Obj.HelloWorld()
str2 = Obj.HelloName(" Everybody")
Obj.Hello()
End Sub
Explanation:
As mentioned, while calling the procedure Hello, parentheses have to be used even
though it does not require any argument. Similar treatment has to done for functions.
Structures Replace User Defined Types
In VB.NET, structures can be defined using Structure keyword. Unlike user defined
types, structures share many features with classes. Explicit mention of access modifier for
each member is necessary in VB.NET. Access modifiers can be Public, Protected,
Friend, Protected Friend, or Private. You can also use the Dim statement, which
defaults to public access.
Let us take an example of a Person that will have some characteristics as Name, Address,
Tel, Age etc. Now if we were to use this number of times, it will be better to have a type
called Person. The example below shows how to handle this.
Structure Person
Structure Person
Dim Name as String
Private Address as String
Dim Tel as String
Public Age as Integer
End Structure
As shown in the above code, explicit mention of the access specifier for each member is a
must.
Structures, like classes, can contain data members as well as data methods. Structures are
value types and are hence allocated on the stack where as classes are reference types and
require heap allocation.
Block Level Scope

The scope of block level variables is restricted to the block in which they are defined.
This block can be a function, procedure, a loop structure etc. A block level variable is not
accessible anywhere, outside its block.
Example:
Consider the sample code segment.
Sub BlockScope()
Dim a As Integer = 1
Dim i As Integer = 1
While (i <= 2)
Dim j As Integer = 1
j = j + 1
i = i + 1
End While
a = a + j
End Sub
Explanation:
The above code segment will give a compile-time error, since the scope of the variable ‘j’
is restricted to the while block and hence it is not accessible outside the while block.
Though block level variables cannot be accessed outside their block, their lifetime is still
that of the procedure containing them.
Early Vs Late Binding
In case of early binding, the compiler knows the object's data type at compile time and
hence can directly compile code to invoke the methods on the object. This enables the
compiler to discover the appropriate method and ensure that the referenced method does
exist and the parameters provided are in sync with that of the referenced method.
Since object types are known ahead of time, the IDE aids the programmer by providing
support for IntelliSense. This helps the programmer do away with any typological and
syntactical errors. If the method being referenced is not found, the programmer is notified
at compile time thus letting him rectify it rather than making him wait till the application
is run.
In case of late binding, the compiler cannot determine the object's data type and thus the
code interacts with the object dynamically at runtime. To make an object late-bound, it is
defined as a variable of type Object. This variable can reference any type of object and
allows programmers to attempt arbitrary method calls against the object even though the
Object datatype does not implement those methods. Since type of the object is not
known until runtime, neither compile-time syntax checking nor IntelliSense is possible.
The typological errors also go undetected until the application is run. However, there is
an unprecedented flexibility, since code that makes use of late binding can talk to any
object from any class as long as those objects implement the methods we require.
The discovery of the referenced method is done dynamically done at runtime and is then
invoked. This discovery takes time and the mechanism used to invoke a method through
late binding is not as efficient as that used to call a method that is known at compile time.
Thus, though late binding is flexible, it is error-prone and slower as compared to early
binding.
When Option Strict is "On", it does not support late binding since the datatype of the
object should be known at compile time.
Example:
Consider the below given code segment
Public Class SampleClass
Public Sub Proc()
MessageBox("This method is discovered dynamically at runtime")
End Sub
End Class
Public Class MainClass
Shared Sub Main()
Dim Obj As Object
Obj = New SampleClass()
Obj.Proc()
End Sub
End Class
Explanation:
The above code segment implements late-binding. There are two classes viz.
SampleClass and MainClass. The class SampleClass contains a procedure named Proc
that takes no arguments. This procedure displays an appropriate message in a message
box. The class MainClass declares a variable Obj of type Object. Thus at compile-time,
the actual data type of the variable is not known. At runtime, the system finds that it is
referencing a variable of type Sampleclass. This reference to the class is achieved using
new operator. The referenced method Proc is discovered at runtime and is finally
invoked.
Ctype Function
Ctype is a general cast keyword that coerces an expression into any type. It returns the
result of explicitly converting an expression to a specified data type, object, structure,
class, or interface. If no conversion exists from the type of the expression to the specified
type, a compile-time error occurs. When Ctype is used to perform explicit conversion,
execution is faster since it is compiled inline and hence no call to a procedure is involved
to perform the conversion.
Syntax: Ctype (expression, type name)
Example:
Consider the below given code segment
Public Class TrialClass
Sub Proc (obj as Object)
Dim Obj1 As OtherClass( )
Obj1 = Ctype (obj, OtherClass)
Obj1.OtherProc( )
End Sub
End Class
Explanation:
The variable Obj1 is of type OtherClass. This class has a procedure named OtherProc.
In the above code segment, the procedure Proc takes one parameter of type Object. The
Ctype statement gains an early bound reference to the object of type OtherClass. Thus
performance benefits of early binding can be achieved.
Changes to Boolean Operators
In Visual Basic.NET, And, Or, Xor, and Not are the boolean operators and BitAnd,
BitOr, BitXor, and BitNot are used for bitwise operations.
VB.NET has introduced the concept of short-circuiting. According to this concept, if the
first operand of an And operator evaluates to False, the remainder of the logical
expression is not evaluated. Similarly, if the first operand of an Or operator evaluates to
True, the remainder of the logical expression is not evaluated.
To perform the above mentioned functionality, VB.NET has introduced two new
operators viz. AndAlso and OrElse. AndAlso performs short-circuiting logical
conjunction on two expressions whereas OrElse performs short-circuiting logical
disjunction on two expressions
Syntax : expression1 AndAlso expression2
expression1 OrElse expression2
Structured Error Handling
The whole idea behind error handling is to accurately trap the error. VB.NET has
introduced a structured approach for handling errors, in order to keep in sync with the
features offered by all Object Oriented languages viz. C#, Java etc. This structured
approach is implemented using a Try…Catch…Finally block structure and is known as
Exception Handling.
Try statement comes before the block of code that needs to tested for errors, Catch
statement handles specific errors and hence surrounds the block of code that handles
those errors and Finally block of code is always executed and contains cleanup routines
for exception situations. Since Catch block is specific to the type of error that needs to be
caught, a single Try statement can have multiple Catch blocks associated with it.
Example:
Consider the below given code segment
Dim num1 As Integer
Dim num2 As Integer
Dim num3 As Integer
Dim str As String
num1 = CType(System.Console.ReadLine( ), Integer)
num2 = CType(System.Console.ReadLine( ), Integer)
str = System.Console.ReadLine( )
Try
num3 = num1 / num2
num1 = CType(str, Integer)
Catch e1 As System.InvalidCastException
System.Console.WriteLine("There is a casting error")
Catch e2 As System.OverflowException
System.Console.WriteLine("There is an overflow error")
Finally
System.Console.Writeline("Please enter valid input")
End Try
Explanation:
The above code segment has been written with an intention of creating an error to explain
the structured way of trapping errors. As shown, it accepts two integers and one string
from the user and tries to divide first number by the second number and also tries to
convert the entered string to an integer. Since the statements that divide the numbers and
perform casting are critical, they are put in the Try…Catch…Finally block structure.
The code segment has two Catch statements viz. first statement handles the casting
(wrong format) error while the second one handles the overflow (division) error.
If the user will enter zero as the second number, then the code will throw an overflow
exception which will be handled by displaying the error message on the Console.
Similarly, if the user will enter a string say "Hello" as the third argument, the code will
throw an invalidcast exception which will be handled by displaying the error message on
the Console. In both the cases, the Finally block of code is always executed. Finally
block is even executed, when there is no error in the program. Thus it is the right place to
perform cleanup routines.
This structured approach provided by VB.NET lets the programmer track the precise
location of the error in the code.
Data Type Changes
Integer
Integer Type VB.NET CLR Type
8-bit Integer Byte System.Byte
16-bit Integer Short System.Int16
32-bit Integer Integer System.Int32
64-bit Integer Long System.Int64
Boolean
A Boolean variable can be assigned one of the two states viz. True or False.
In VB.NET, when numeric types are converted to Boolean values, 0 becomes False and
all other values become True.
When Boolean values are converted to Integer values, True maps to -1 and False maps
to 0.
String
To be inline with other .NET languages, VB.NET has updated string length declaration.
In VB.NET, you cannot declare a string to have a fixed length. You must declare the
string without a length. When a value gets assigned to the string, the length of the value
determines the length of the string.