You are on page 1of 41

Contents

Authors

Introduction

1. Visual Basic.Net - An introduction

2. Classes

3. WinForms

4. Access Modifiers

5. Database Handling

6. XML

7. Exception Handling

8. Basics

9. Classes, Interfaces and


Structures

10. Parameters to Procedures


Authors
Vijay Mukhi (vmukhi@vsnl.com) is one of the pioneers of the Indian Infotech
Industry. For years, he has been the first to teach the emerging technologies in India
thus ensuring that India always has people trained in technologies that the world
requires. Vijay has written over 80 books on computers and programming over the
last eight years on subjects ranging from C, C++ (The Odyssey Series) to Animation
and Networking to Java to C#. Vijay abhors complexities and hence his books
showcase the most difficult concepts explained through small programs, thereby
giving a good understanding. Microsoft's .Net technologies is what Vijay is now
focusing on and he aims at writing volumes on it. His knowledge on .Net
Technologies is clearly visible in his seven books where he explains the different
concepts relating to Visual Studio.Net in the most simplified form.

Deepak N. Ramchand (tulipapparels@vsnl.com) is an enterprising apparel


exporter, a creative designer by choice. Deepak, being very ambitious in life and
specializing in the field of fashion technology, aims to create his own mark and
presence in the area he adopts. In the application of computer technology to his
knowledge of fashion creativity, this is his first stepping stone.

Sonal Mukhi (svmukhi@yahoo.com) is a freelance programmer having a widespread


exposure to computer techniques and languages. Sonal has done groundbreaking
work on various Internet Technologies like Java, ActiveX, Perl, C# and more. She has
co-authored a few books on computer programming too.
Introduction
The .NET Framework, encompassing a great new product called Visual Studio.NET, is
tipped to spur a revolution in the software industry. This is because, the .Net
Framework and Visual Stodio.Net have been designed with the Internet as their
epicentre.

Visual Basic has been the most widely accepted programming language in the world,
and also enjoys the distinction of having the largest band of loyal programmers.
Thus, Microsoft was left with no choice but to integrate this product into the .NET
Framework in the form of VB.NET. In order to accommodate the large troupe of
existing VB developers within this framework, Microsoft has introduced a number of
contemporary features to VB.NET, and greatly ameliorated its web design facilities.
VB.NET is also regarded as the easiest entry-point into the .Net world, that provides
succour to those who are terrified of biting the bullet of the Brave New World of
technology.

Microsoft has retained the heart and soul of the original VB product, while
simultaneously embellishing it with the latest developments available in software
technology. This forms the genesis of VB.NET. As a result, Visual Basic.NET is
primarily an extension of the Visual Basic programming language, which is shipped
with the Visual Basic product. However, it is a significant upgrade or improvement
over VB and is far more flexible and powerful.

This book is for the dilettante, and aimed at anyone who is interested in learning
VB.NET. The approach that has been followed here is that simple applications are
built first, and then, the code is deciphered to unveil the internal workings of the
product.

However, in order to thoroughly appreciate the internal execution of the programs,


there are certain significant concepts of the language that need to be discerned first.
We have ferreted out the relevant concepts and presented them in the most
elementary manner.

This book converges predominantly around the language aspect, to provide


enhanced insights to the programmer into the innovative and improved features of
VB.Net. We are of the opinion that on learning the language, large applications can
be designed with effortless ease.

This book is also endowed with a generous sprinkling of error messages, since we
believe that by studying the cause of the errors that are generated by programming
languages, programmers are bound to become more astute.

We have ensured that your interest does not evaporate, by making the book as
entertaining and informative as possible. We have done our best to bring our aim of
making you a good VB.NET programmer, to fruition.
Finally, we leave it to you to decide whether the VB.NET product has really lived up
its expectations or not.

Minimum Requirements

The software requirements to successfully run all the programs in this book are

• Operating System - Windows 2000, Windows XP


• Microsoft IIS ver 5.0
• SQLServer 2000
• Visual Studio.Net

Visual Studio.Net
You can ask for your copy of this software from Microsoft by placing an order for the
same on their website.

SQLServer 2000
While installing the evaluation edition of SQLServer 2000, we have chosen the default
selected settings. The only modification made is in the Authentication Dialog Box.

You see two options


• Windows Authentication mode
• Mixed mode (Windows Authentication and SQL Server Mode)

The default option selected is Windows Authentication mode. We have instead


selected Mixed mode (Windows Authentication and SQL Server Mode). Once this
option is selected, the password text boxes for the 'sa' user gets activated. As we
would prefer using a blank password in our programs, we select Blank Password. On
selecting this option, the text boxes get disabled again.

Acknowledgements
The many individuals who have worked together to produce this great work of art
and motivated me all the way need a mention here. Their bright ideas, inspiration,
support has made me a lot more stronger and wiser.

First and foremost, thanks to Manish Jain, BPB Publications for publishing the book.

To my co-authors, Deepak and Sonal who have put in a lot of hard work to complete
the work assigned to them.

To Tanuja Sodhi, an ex-Naval Officer from the first batch of lady officers and an
MBA from Jamnalal Bajaj, for editing the book. She is presently freelancing as a
creative writer.

To Altaf Hemani and Kishore Rohra, for their creativity in designing the cover.

Thanks to Manish Purohit for putting in all the time he had to verify the code with
the explanations and then giving the book a good look and feel.

To Pradeep Mukhi and Shivanand Shetty, who have always been there, as a
source of inspiration and encouragement.
My Mother, Shana Aunty and a long list of friends need a mention here for their
patience and cooperation on this book while it was being written.

1. Getting Started
In this book, we work under the basic assumption that you have no inkling about any
of the programming languages, and VisualBasic.Net in particular. But, you would
invariably have heard people fantasizing about the great new product called Visual
Studio.Net, which is in the reckoning to bring about a revolution in the software
industry.

So, let us get to the meat of this product. We shall gain a meticulous understanding
of this language and its features, and only then shall we decide whether the claims
made by the populace are justified or not. We could keep extolling the virtues of the
finer things in life, but we'd rather get down to brass-tacks straightaway. We assume
that you have a copy of Visual Studio.Net installed on your machine.

To launch Visual Studio, click on the ubiquitous Start Button in Windows. (In our case,
we have installed Windows 2000). Then, click on Programs, followed by Microsoft
Visual Studio .Net. Finally, select the option of Microsoft Visual Studio .Net. This is
shown in the Screen 1.1.

Screen 1.1
Shortly thereafter, a window pops up, showing Visual Studio.Net in all its glory, as
shown in screen 1.2.
Screen 1.2
Hey, hang on! Could there be something amiss with what you are doing? Your copy of
Visual Studio .Net could be displaying something totally different!! Yes, this could be
a distinct possibility!

One of the salient features of present day software is that it can be customized to a
large extent. This is why the final appearance of a product could be drastically
different from what it originally looked like, when freshly taken out of the box. Thus,
the screen 1.2 will never look identical on all the machines. We shall explicate these
differences in due course, but for the moment, we are exceedingly inclined towards
embarking upon the development of a small application or project. But before
venturing any further, close all the child windows by clicking on the x sign.

Then, click on the menu option File, followed by New, and finally Project. This
becomes evident in screen 1.3.
Screen 1.3
The above actions will result in the display of the Dialog box titled "New Project". This
is shown in screen 1.4.

The advantage of using Visual Studio .Net is that diverse applications, each using a
different programming language, can be developed simultaneous, under a single
streamer.

This explains why three language options are present in the first pane of the dialog
box, viz. Visual Basic, Visual C# and Visual C++.

Screen 1.4
The option of Visual Basic project is listed first. Hence, it is highlighted by default.
This signifies the priorities of Microsoft, and is the very raison de etré of this book!
A perfect analogy for Visual Studio .Net is that of a glass, which can be used to drink
either water or juice or wine. In a similar fashion, under the single roof of Visual
Studio .Net, various programs developed in different languages, can be written. The
language used is simply not an issue.

The second pane titled 'Templates' determines the type of application that would
eventually be created. This could be an executable file running under Windows, or a
Web Application running a web server.

Since we are naïve about this product, we select the option of Windows Application.
This option is selected by default.

The next task is to specify a name for the project. We have chosen the name 'vvv',
since we sincerely believe that it will bring us good tidings on our very first
application. We have used our newly created folder called 'v1' as the location for
creating the application. You are at liberty to choose any folder that you fancy.

Screen 1.5
After specifying all the details as shown in screen 1.5, click on the OK button.

This brings us to Screen 1.6, where we encounter an empty form.


Screen 1.6
Now, in order to view the output of our handiwork, click on the menu option Debug,
and then on Start. This is shown in screen 1.7.

Screen 1.7
This ignites the excitement of Visual Studio .Net, and it starts processing the request.
Finally, as the outcome of the operation, it displays an empty form, as seen in screen
1.8. This is no mean achievement for people like us, considering the fact that we
have not written even a single line of code yet!
Screen 1.8
Close this form window by clicking on the x sign on the right hand side. This will
revert us back to the form in Visual Studio .Net. The next task that we venture upon
is, to display a button on the form. To accomplish this, click on the menu option View,
and then, on the option of ToolBox, as shown in screen 1.9.

Screen 1.9
This option brings up a toolbox containing a list of objects or controls. The toolbox
window is visible on the left hand side of the screen, as revealed in screen 1.10.
Screen 1.10
Now, simply click on the control labelled as Button to select it, and then, drag and
drop it into the form. Screen 1.11 displays the position where we have dropped our
button.

Screen 1.11
Then, run the application in the customary manner by clicking on the menu Debug,
and then, click on Start. Screen 1.12 confirms that the form now contains the button
in it. Pat on the back! Having covered just a couple of pages, we have already placed
a button on the form.
Screen 1.12
The shortcoming of our present endeavour is that, we are clueless about what is
going on behind the scenes. Clicking on the OK button in the New Project dialog box,
results in the generation of considerable amount of code by the Visual Studio .Net
framework. Apparently, we have merely clicked on the ToolBox, which is a User
Interface tool; and then, we have dragged and dropped a button in the form.
However, in reality, ample code has been generated in the background to accomplish
this seemingly simple task.

We are convinced that prior to forging ahead with the task of building complex
applications using Visual Studio .Net, there is a need for discerning the code that it
generates. Also, along the way, we shall keep reverting back to the Visual Studio
.Net framework, to demonstrate as to how it has made a programmer's life more
easygoing. However, you have to learn a programming language that is to be used
with it, since it is a fundamental fact that Visual Studio .Net cannot build customized
applications by itself. It is the task of the programmer to program it to satisfy the
specific requirements.

So, we start by writing the smallest Visual Basic program. As is customary in all our
books, we shall refrain from attempting to impress you with our knowledge of
programming. Instead, we shall proceed systematically, a single step at a time. So,
here we go!

First, create a folder named il on your hard disk. Then, using a text editor such as
Notepad, create a file called a.vb, with the following contents in it:

a.vb
Module zzz
End Module

To execute the above code, go to the Visual Studio .NET Command Prompt (Start->
Program-> Visual Studio .Net-> Visual Studio .Net Tools-> Visual Studio .NET
Command Prompt), and run a program called vbc. We achieve it as follows:

c:\il>vbc a.vb
This action of ours results in the following error message:

vbc : error BC30420: 'Sub Main' was not found in 'a'.

Every Visual Basic program must be enclosed within the words 'Module' and 'End
Module'. There is no rational explanation for this prerequisite. So, we accept it as the
dictum. Every Module requires a name. So, we have chosen the name 'zzz'. This
name has been deliberately chosen to demonstrate that the name per se, is not very
significant. Any name would suffice, as long as one is present. An empty module is
forbidden. Further, the error message displayed earlier clearly mandates the
presence of a function or a sub-routine called Main.

a.vb
Module zzz
Sub Main()
End Sub
End Module

After we insert two lines within the Module, the compiler successfully compiles
without any hiccups. In the directory, you will see a file called a.exe, which when
executed, does not display anything.

Visual Basic is a case-insensitive language. However, we still follow the Microsoft


convention of writing the word Module with a capital M, even though we are at liberty
to determine our own capitalization rules.

After having attended to the first rule of Visual Basic, i.e. enclosing the code within
the words 'Module' and 'End Module', we progress onto the second rule, which insists
on the presence of a sub-routine called Main. The word 'sub' is a short form for the
term sub-routine, which takes a name along with it. It is merely a collection of code.

A sub-routine is created in a manner similar to the creation of a module, where we


begin with the word Sub, followed by the name of the sub-routine, i.e. Main. Finally,
the subroutine has to conclude with the word 'End', followed by the word 'Sub'. A
'Sub' can have a pair of open and close brackets. However, they are optional. So, on
odd days we write 'Sub' with brackets in our programs, while on even days, we omit
them ;-).

The Visual Basic language is verbose and rather lax in its rules. Now, let us write a
program that displays a string.

a.vb
Module zzz
Sub Main()
System.Console.WriteLine ("Hello")
End Sub
End Module

Output
Hello

On compiling and executing the above program, we are greeted by the word "Hello"
in the output. It has been an ancient programming tradition wherein, the first
program in any programming language displays the word "Hello". The word "Hello"
gets displayed on the screen because a function has been executed or called.

In a programming language, a function name constitutes a word, followed by a pair of


round brackets.

Thus, Main is a function, since it ends with a pair of round brackets. However, there is
a subtle difference, which is:
• In the case of Main, we were creating a function or a sub-routine, since the
line started with the word 'Sub'.
• In the case of System.Console.WriteLine ("Hello"), the word 'Sub' is not
present. Hence, it construes that a function or subroutine is being called for
execution.

There is a minor distinction between a subroutine and a function, which we shall


attend to later on, in the chapter.

The name of our function i.e. System.WriteLine.Console, is considerably long. We


need not torment ourselves about the details of how this function has been written,
at this stage. We only have to be conscious of the fact that it requires some words to
be inserted within double quotes, which it will display on the screen.

Since we have specified the word Hello within double quotes, the console displays the
word "Hello". This is the mechanism of passing data or parameters to a function. This
function is one of the innumerable ones that are available in Visual Basic. We can use
them on multiple occasions in our code.

a.vb
Module zzz
Sub Main
System.Console.WriteLine ("Hello")
System.Console.WriteLine (100)
End Sub
End Module

Output
Hello
100
A single function is capable of embodying multiple lines of code. In the above
program, we have called the function System.Console.WriteLine twice:
• On the first occasion, we have passed a string or a sequence of letters of the
alphabet as a parameter.
• On the second occasion, we have passed it a number.

The function dutifully prints out both the values without complaining at all.

a.vb
Module zzz
Sub Main
System.Console.WriteLine (vijay)
End Sub
End Module

Error
c:\il\a.vb(3) : error BC30451: Name 'vijay' is not declared.
System.Console.WriteLine (vijay)

In the WriteLine function, we have specified the word vijay, without enclosing it
within inverted commas. The Visual Basic product or compiler reverts back with an
error, expressing its ignorance about the name vijay. It expects it to be declared
explicitly.

a.vb
Module zzz
Sub Main
dim vijay
vijay = 100
System.Console.WriteLine (vijay)
End Sub
End Module

Output
100

To create or declare any valid name, the line must begin with the word DIM, followed
by the name, thereby, informing VisualBasic.Netthat a name is being created. Thus,
'DIM vijay' signifies that the name vijay is being declared. These names are created
so that they can store values in them. On the next line, we have specified a value of
100 to be stored in the name vijay.

An elementary rule in all programming languages is that, a number or a string may


be substituted by a name that holds the value. Therefore, when the function
WriteLine is furnished with the name vijay, no error is generated. This is because, the
framework first identifies the value contained in it. Since vijay holds the value of 100,
it is displayed on the screen.

a.vb
Module zzz
Sub Main
dim vijay
vijay = 100
System.Console.WriteLine (vijay)
vijay = 200
System.Console.WriteLine (vijay)
vijay = vijay + 10
System.Console.WriteLine (vijay)
vijay = vijay + 1
System.Console.WriteLine (vijay)
End Sub
End Module

Output
100
200
210
211
As was done in the program above, we create a name vijay and assign it a value of
100. Then, using the WriteLine function, the value is displayed. vijay is then re-
assigned a new value of 200, which is also displayed. Thus, the value stored in vijay
can vary. Due to this ability to hold varying values, words such as vijay, are termed
as variables.

On the next line, we have performed an arithmetic operation by presenting the


statement vijay = vijay + 10. On encountering a line containing an 'equal to' sign =,
initially all attention is riveted on the expression that is on the right side of the sign.
This expression is 'vijay + 10'. So firstly, the value of vijay is evaluated to obtain a
value of 200. Then, 10 is added to it, in order to obtain a result of 210.

This value is now assigned to the variable on the left hand side of the 'equal to' sign,
i.e. vijay, thereby updating its value. Thus, when the variable vijay is displayed, it
shows the value of 210. In the next round, the value of the variable is increased by 1,
thus, making the final value as 211.

The concept of variables is one of the pillars on which the programming world rests.
Here, a word or name holds a value, which can keep fluctuating.

a.vb
Module zzz
Sub Main
dim vijay
vijay = 100
System.Console.WriteLine (vijay)
vijay = "hi"
System.Console.WriteLine (vijay)
End Sub
End Module

Output
100
hi

In this example, the variable vijay is first assigned a numeric value 100. Then, it is
assigned a string value of "hi". Nobody complains and both values get displayed.
Thus, we have the license to change the data type of the value that the variable can
hold.

a.vb
Module zzz
Sub Main
dim vijay as integer
vijay = 100
System.Console.WriteLine (vijay)
vijay = "hi"
System.Console.WriteLine (vijay)
End Sub
End Module

Output
100
Unhandled Exception: System.InvalidCastException: Cast from string "hi" to type
'Integer' is not valid. ---> System.FormatException: Input string was not in a correct
format.
at Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value,
NumberFormatInfo NumberFormat)
at Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value)
--- End of inner exception stack trace ---
at Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value)
at zzz.Main()

The previous program does not demonstrate the conventional technique of


programming, because a variable must essentially represent only a single type
during its lifetime. To maintain absolute consistency, the data type is specified while
creating the variable.

This is achieved by adding the word 'as' after the DIM variable, followed by a
predefined data type. vijay is assigned the data type of integer, which implies that
the variable vijay shall store only numbers or integers.

After displaying the number that it contains, the variable vijay is then initialized to a
string value of "hi". The earlier program had not protested under similar
circumstances.
However, now we come across a mammoth dialog box displaying an error message.
When we click on No, we observe the above error on the console.

This error or exception enucleates the fact that, we are not empowered to specify a
string value for a variable that has been declared to be of type integer. Henceforth,
we shall declare all our variables with a data type.

a.vb
Module zzz
Sub Main
dim i,j as integer
i = 10
System.Console.WriteLine ("{0} {1}", i, j)
End Sub
End Module

Output
10 0

In a single stroke, we have the ability to create as many variables as we wish,


separating each one of them with a comma. The above example has two integer
variables named i and j, which have been declared together. The variable i is
assigned a value of 10, while j is not initialized at all. In the same manner that was
used to create two variables simultaneously, we now wish to print their values too in
a single stroke.

To accomplish this, the WriteLine function has been modified and assigned a string
that has the numbers 0 and 1 enclosed within curly braces. This string parameter is
followed by the two variables i and j, separated by commas. They are extra
parameters.

The WriteLine function replaces the first curly brace of 0, with the value of the first
parameter after the string i.e. i, and the second curly braces of 1 with the second
parameter after the string, i.e. j. Since the value of the variable i is 10, and the value
of the variable j is 0, the output that is displayed is 10 0. Thus, not only have we
learnt how to print multiple variables using a single WriteLine function, but have also
become wiser by the fact that, if a variable is not assigned a value, it obtains a
default value of 0.

a.vb
Module zzz
Sub Main
dim b as boolean
dim i as integer
dim j as string
j = "hi"
i = 10
b = true
System.Console.WriteLine ("{0} {1} {2} {3}" , i > 20 , i < 20 , b , j = "hi")
End Sub
End Module

Output
False True True True

A data type represents a specific type of data. In the above example, we have
created three types of variables:
• i is of type integer
• j is of type string
• b is of type Boolean.

A Boolean type can store only one of the two values, true or false.

The variable i of type integer can hold any valid number. It is assigned the value of
10.

The variable j, of type string, must have its value enclosed within double inverted
commas. It is assigned a value of "hi".

The boolean variable b is initialized to a value of true.

In the WriteLine function following the string, we first display the expression i > 20,
instead of the variables. Doing so, indirectly poses the question "Is the variable i
greater than 20?"
The result can either be true or false. Since the value of the variable i is 10, which is
less than 20, the value of False is displayed. The second expression determines
whether the value of i is less than 20 or otherwise. Since this is affirmative, the value
of True is displayed on the screen.

The third parameter to the WriteLine function simply displays the value of the
boolean variable b. The value of the boolean variable is not altered from what it was
initialized to. Hence, the output is displayed as True.

The last check performed is, whether the value of the string j is equal to the string
value "hi" or not. Since they both are the same, the resultant value of True is
displayed. Thus, all the above expressions result in a boolean value of either true or
false.

a.vb
Module zzz
Sub Main
dim i as integer
i = 10
if i > 50 then
System.Console.WriteLine ("Condition True")
End if
if i > 5 then
System.Console.WriteLine ("Second Condition True")
End if
End Sub
End Module

Output
Second Condition True

The programs that we have presented so far are absolutely straightforward, since
every line of code that is entered, gets called sequentially. We desire to execute code
based on certain circumstances.

The above program is the perfect prescription for this. We have created an integer i
with a value of 10. Then, we encounter an 'if' statement.

An 'if' statement is always followed by a condition or an expression, and the line ends
with a 'then'. In the first case, a check is performed to determine whether the value
of the variable i is larger than 50 or not. Since the answer is False, all the lines of
code leading up to the 'End If', are ignored. Thus, the first WriteLine function with the
Condition True, does not get executed at all.

The condition with the second 'if' statement, verifies whether the value of i is greater
than 5 or not. Since it is, all the code between the 'if' and the 'end if' is
executed. Thus, an 'if' statement is used to make decisions, i.e. to intelligently
execute specific code, depending upon whether some variables have certain values
or not. In this manner, we can effortlessly write intelligent and dynamic programs.

a.vb
Module zzz
Sub Main
dim i as integer
i = 10
if i > 50 then
System.Console.WriteLine ("Condition True")
else
System.Console.WriteLine ("Condition False")
End if
if i > 5 then
System.Console.WriteLine ("Second Condition True")
End if
End Sub
End Module

Output
Condition False
Second Condition True
In the above program, the 'if' statement now has the 'else' clause added to it. In the
earlier program, when the result of the 'if' statement was false, no code was
executed.
Now, since the 'else' clause has been added, whenever the 'if' statement is false, the
statements within the 'else' block are executed. So, all code from the 'else' upto the
'end if', is executed. When the 'if' condition results in True, the statements contained
within the 'if' upto the 'else', are executed.

The advantage of using the 'else' clause is that, some code finally gets executed.
However, the 'else' clause is optional.

Subroutines

a.vb
Module zzz
Sub Main
abc
End Sub
End Module

Error
c:\il\a.vb(3) : error BC30451: Name 'abc' is not declared.

By introducing the name abc, we have attempted to call a subroutine or a function by


that name. Like before, an error is generated, since abc has not been declared. Thus,
as in the case of variables, we have to declare or create the subroutine or function
before calling our own code.

a.vb
Module zzz
Sub Main
abc
End Sub
sub abc
System.Console.WriteLine("in abc")
end sub
End Module

Output
in abc

At the very outset, we had created a subroutine called Main, by using Sub.
Harnessing the same mechanism, we now create another subroutine called abc.

The only difference between the two sub-routines is that the code in Sub Main is
called when the .exe file is executed, whereas, the code in the other subroutines has
to be called explicitly.

To execute code in a subroutine, just the name of the subroutine has to be specified
on a blank line. Hence, we have merely specified the name abc. This action calls the
code in the subroutine, thereby resulting in the WriteLine function being called, with
the string 'in abc'. This sounds too easy to be true!

a.vb
Module zzz
Sub Main
abc
pqr
End Sub
sub abc
System.Console.WriteLine("in abc")
pqr()
pqr
end sub
sub pqr
System.Console.WriteLine("in pqr")
end sub
End Module

Output
in abc
in pqr
in pqr
in pqr

We can create as many subroutines or subs as we like in a single module. The above
program displays two subroutines, both of which are called from the Main block.
Furthermore, the pqr subroutine is called twice from the abc subroutine.
Thus, we enjoy the privilege of calling code contained in any other subroutines, as
many times as we desire. You would notice that at one stage we had called the pqr
subroutine, using the open and close brackets. The brackets are optional. So, their
presence or the lack of it, does not interfere much with the execution of the code.

a.vb
Module zzz
Sub Main
abc("Hi")
End Sub
sub abc()
System.Console.WriteLine("hell")
end sub
End Module

c:\il\a.vb(3) : error BC30057: Too many arguments to 'Public Sub abc()'.

In the above example, an error is generated, since we are passing the string
parameter "Hi" to the sub abc; whereas, the sub abc has not been declared to accept
any parameters. So, let us rectify this situation in the subsequent example.

a.vb
Module zzz
Sub Main
abc("Hi")
End Sub
sub abc(s as string)
System.Console.WriteLine(s)
end sub
End Module

Output
Hi

The above example demonstrates the correct way of creating a subroutine. The
string "hi" is passed as the value for the variable 's' in the sub abc. The variable 's' is
termed as a parameter. It is supplied to the WriteLine function for display purposes.
Subroutines that accept parameters are very practical and efficacious, since they
infuse a lot of flexibility and generality into the program.

a.vb
Module zzz
Sub Main
Dim s,t,u as string
s = "hi"
t = "bye"
u = "No"
abc(s,t,u)
System.Console.WriteLine("{0} {1} {2}",s,t,u)
End Sub
sub abc(s0 as string , byval s1 as string, byref t1 as string)
System.Console.WriteLine("{0} {1} {2}",s0,s1,t1)
s0 = "good"
s1 = "bad"
t1 = "ugly"
end sub
End Module

Output
hi bye No
hi bye ugly

In the above example, there are three string variables viz. s, t and u. They are
initialized to "Hi", "Bye" and "No", respectively. These three variables are then
furnished as parameters to the subroutine abc.

In the Sub, the values passed by the three variables, are stored in the parameters s0,
s1 and t1. We will explore the other parameter details in a short while.

Thereafter, the three values are displayed using the WriteLine function. Then, the
values of the parameters s0, s1 and t1 are modified to some other values. Once the
subroutine abc ends, the control moves on to the next line in the Main block.

Here, we again use the WriteLine function to display the values of the variables s, t
and u. To our utter astonishment, we discover that the value of the variable 'u' is
different from what it had been initialized to. It displays the new value that has been
assigned to it in the abc subroutine. However, s and t retain their old values.

In sub abc, we have changed the values of the parameters, and not the original
variables. Notwithstanding this, the value contained in the variable 'u' within the
main subroutine, changes. This is because of the fact that, we have affixed the word
'byref' before the name of the parameter. This word signifies that if the parameter t1
changes in the sub abc, the original variable in the calling Sub would also change
correspondingly.

By using the word 'byval', any changes made to the value of the variable in the
subroutine, would not percolate down to the original variable.
The default is 'byval', and since it has not been mentioned for the first parameter, the
effect is that of byval. Thus, it is the sub that decides on whether to reflect the
changes made, onto the original variable that is passed as a parameter.

a.vb
Module zzz
Sub Main
Dim s as string
s = "hi"
abc()
End Sub
sub abc()
s = "No"
end sub
End Module

Error
c:\il\a.vb(8) : error BC30451: Name 's' is not declared.

We did not enlighten you earlier about a very essential feature of Sub. However, this
seems to be an opportune time to divulge the fact that, a Sub is an independent and
a self-contained entity. The variable 's' created in the sub main, is not discernible in
the sub abc. Hence, the compiler generates the above error.

a.vb
Module zzz
Sub Main
Dim s as integer
s = abc(10,20)
System.Console.WriteLine(s)
End Sub
Function abc(i as integer , j as integer) as integer
abc = i + j
end Function
End Module

Output
30

Your reaction to this book could range from being extremely positive to being
outright negative and unimpressed. This would depend upon how well you relate to
our style. It has always been our endeavour to explain only a single concept at a
time. This could get exasperating for a large number of people.

The above example highlights the difference between a sub and a function. They are
almost identical, but for one variation, i.e. a function can return a value, whereas, a
Sub cannot.

In many situations, returning values is very important because functions normally


perform certain tasks and return the result of their operation. The above function abc
accepts two integers parameters and returns their sum.

Creating functions is a child's play, since it entails replacement of the word 'Sub' with
the word 'Function' and the words 'End Sub' with the words 'End Function'. The words
'as Integer' signify that the function will return an integer when it is called. To return
a value in a function, the name of the function has to be initialized to the specific
value. Thus, writing abc=100 will return 100.
In our case, we are adding up the two parameters 10 and 20, and initializing the
function name abc with the sum of 30. Thus, the variable s in the sub main will now
have a value of 30, which is the return value of the Function.

a.vb
Module zzz
Sub Main
Dim s as integer
s = abc(10,20)
abc(100,300)
System.Console.WriteLine(s)
End Sub
Function abc(i as integer , j as integer) as integer
abc = 300
abc = i + j
end Function
End Module

Output
30

You may set the return value as many times as you like. No one would whine. The
last value to be returned will be the one that is finally used. Thus, the return value of
300 is overridden by the last value to be returned, i.e. 30.

Even though it is the job of a function to return a value, we can avoid storing the
return value in a variable. Thus, in the second round, when the function abc is called,
we do not save its return value in a variable. However, nobody makes a fuss about it.

As has been oft repeated by us, VisualBasic.Netis a very forgiving and flexible
language, and that is precisely why we love it as much as we do!
2. Classes
Visual Basic has never been considered to be a clean programming language. This
became a Gordian knot for Microsoft and began brewing trouble. However, in spite of
this setback, amazingly, no other product has sold more copies than Visual Basic in
the history of the computing world. Thus, Microsoft has no choice but to retain the
heart and soul of Visual Basic, and simultaneously, embellish it with the latest
features available in language technology. This forms the genesis of Visual Basic.Net.
Visual Basic .Net is primarily an extension of the Visual Basic programming language
that is shipped with the Visual Basic product.

In Visual Basic.Net, which is the improved version of Visual Basic, we can replace the
word 'module' with the word 'Class'. Together with this modification, one more
change is required, i.e. the word 'Shared' has to be added to the Sub Main. If the
main subroutine is not amended to 'shared', the following error crops up:

Error
vbc : error BC30737: No accessible 'Main' method with an appropriate
signature was found in 'a'.

a.vb
Class zzz
Shared Sub Main
System.Console.WriteLine("hi")
End Sub
End Class

Output
hi

Now, when we compile and run the program, the code in Main gets called, displaying
the word "hi". A class is an entity like a module, which carries code and variables.

a.vb
Class zzz
Shared Sub Main
abc
End Sub
Shared sub abc
System.Console.WriteLine("in abc")
end sub
End Class

Output
in abc

The above example has a subroutine called abc, with the word 'Shared' added to it. If
the word 'Shared' is omitted, the compiler generates the following error:

Error
c:\il\a.vb(3) : error BC30369: Cannot refer to an instance member of a class
from within a shared method or shared member initializer without an explicit
instance of the class.

Let us now delve upon what the word 'Shared' signifies.

a.vb
Class zzz
Shared Sub Main
dim a as zzz
a = new zzz
a.abc
pqr
zzz.pqr
End Sub
sub new()
System.Console.WriteLine("in new")
end sub
sub abc
System.Console.WriteLine("in abc")
end sub
shared sub pqr
System.Console.WriteLine("in pqr")
end sub
End Class

Output
in new
in abc
in pqr
in pqr

The above program has Main and pqr subroutines marked as 'shared', whereas, the
others remain unmarked.

In Sub Main, we first need to create a variable named 'a' of type 'zzz'. Here, we are
not actually creating an object or variable 'a' of type zzz, but merely stating that the
variable 'a' looks like the class zzz. This is akin to creating variables of a certain type.
Also, we can safely presume that integer, string and long are all classes. The
difference is that the Visual Basic.Net compiler is aware of the fact that these classes
are data types.

zzz is a user-defined datatype, which the compiler is oblivious to. Hence, we need to
create an actual instance or occurrence of this datatype. By using the keyword 'new',
an instance or an object of type zzz is created. The line a = new zzz creates a new
object zzz in memory, and returns a handle that is stored in 'a'. To frame it
differently, 'a' represents a fresh zzz object in memory.

An object is an instance of a class. Thus, the statement 'DIM i as integer' creates an


object i, which is an instance of class integer. For the basic in-built data types such as
string, boolean and integer, there is no need to explicitly mention 'new', which is
otherwise mandatory for the user-defined types.

In Visual Basic.Net, the keyword 'new' first allocates memory for all the class
contents, and then, it checks for a sub called 'New'. If the sub 'new' exists, it
executes the code present in it. In most other languages, the sub new() is equivalent
to a constructor of a class. After the subroutine ends, a zzz object is created and
stored in 'a'. The object 'a' can then be used to call the other members in the class.

Initially, the abc procedure is called and then, the sub pqr is called twice:
• At the first instance, without the use of the prefix 'a'.
• At the second instance, using the class prefix.

The word 'shared' implies that the function can be called without creating an object.
Since abc is not shared, we have to create an instance of a zzz object, in order to
access it. The pqr sub is marked as 'shared'. Therefore, it does not require an
instance of an object to access it.

We normally preface a member with the name of the class, which is the default, if not
specified expressly. The sub of main also is marked as 'shared'. Therefore, it does not
require an instance of the class zzz before it can be used.

Prior to venturing further into the concept of Shared, let us anatomize the concept of
a constructor.

a.vb
Class zzz
Shared Sub Main
dim a as zzz
a = new zzz
End Sub
sub new(i as integer)
System.Console.WriteLine("in new {0}", i)
end sub
End Class

Error
c:\il\a.vb(4) : error BC30455: Argument not specified for parameter 'i' of
'Public Sub New(i As Integer)'.

Earlier, the constructor did not accept any parameters. Thus, we were able to call it
without any parameters. In the above program, we have a constructor that expects
one parameter of type integer. However, in the process of creating an instance of the
object zzz, we have not furnished any parameters to 'new'. This results in an error.
a.vb
Class zzz
Shared Sub Main
dim a as zzz
a = new zzz(10)
End Sub
sub new(i as integer)
System.Console.WriteLine("in new {0}", i)
end sub
End Class

Output
in new 10

We have now redressed the above error by passing a parameter to the 'new'
statement. So, when the constructor gets called, the value received in the parameter
i is 10. This value is displayed on the Console. A constructor can be equipped to
accept as many parameters as we wish to supply it.

a.vb
Class zzz
Shared Sub Main
dim a as zzz
a = new zzz(10)
a.new(10)
End Sub
sub new(i as integer)
System.Console.WriteLine("in new {0}", i)
end sub
End Class

Error
c:\il\a.vb(5) : error BC30282: Constructor call is valid only as the first
statement in an instance constructor.

Unlike a subroutine, a new constructor cannot be called explicitly. An error is


generated in the above program, since we are attempting to call a constructor by
itself. Thus, a constructor gets called automatically only when the object is created,
and not otherwise. Further, it cannot be called manually.

a.vb
Class zzz
Shared Sub Main
dim a,b as zzz
a = new zzz(10)
b = new zzz()
End Sub
sub new(i as integer)
System.Console.WriteLine("in new {0}", i)
end sub
sub new()
System.Console.WriteLine("in new ")
end sub
End Class

Output
in new 10
in new
We can have innumerable constructors or 'new' statements in the program, provided
each is assigned different parameters. The above program has two new subroutines,
the first one accepts a single integer parameter, while the second one does not take
any parameters. This program is perfectly valid.

The concept of using the same function name with different parameters is called
'function overloading' or 'sub overloading'.

Now, we present another example on 'function overloading'.

a.vb
Class zzz
Shared Sub Main
abc()
abc(10)
abc("hi")
End Sub
shared sub abc(i as integer)
System.Console.WriteLine("in abc {0}", i)
end sub
shared sub abc()
System.Console.WriteLine("in abc ")
end sub
shared sub abc(k as string)
System.Console.WriteLine("in abc {0}", k)
end sub
End Class

Output
in abc
in abc 10
in abc hi

In the above example, we have three subs with the same name 'abc', but each of
them has different parameters. Out of the three, two subs have the same number of
parameters, but their data types are distinct.

This is permitted, since the name of a function in Visual Basic.Net does not consist of
the name alone, but is composed of the name and the data type of each parameter.
Thus, the name of the first sub abc that accepts an integer parameter, could be
represented by 'abci', where i is the data type of the parameter. The last sub could
be represented by 'abcs', where s stands for the string type of the parameter. This
naming concept initiates uniqueness in the function names.

This concept is known as 'name mangling', where the signature of the function
depends upon both, the name of the parameters and their datatypes.

Now, we present yet another example on constructors to make the concept of


constructors crystal clear.
a.vb
Class zzz
Shared Sub Main
dim a as zzz
a = new zzz()
End Sub
End Class

a.vb
Class zzz
Shared Sub Main
dim a,b as zzz
b = new zzz()
End Sub
sub new(i as integer)
System.Console.WriteLine("in new {0}", i)
end sub
End Class

Error
c:\il\a.vb(4) : error BC30455: Argument not specified for parameter 'i' of
'Public Sub New(i As Integer)'.

Let us comprehend the concept of constructors by examining the above two


examples. The first example compiles without any errors, despite containing no
constructor code.

Visual Basic.Net is not complaining for the reason that, when the program does not
contain any constructors, the complier introduces one of its own, as follows:

Sub new
End sub

Thus, when a constructor is not created explicitly, the compiler creates one for us.
This constructor does not accept any parameters, nor does it do anything. However,
if we include even a single constructor, this complimentary constructor is carted-off
or taken away. Thus, in any situation, there would always be at least one constructor
present in the code.

In the second example, a constructor with one parameter is present. Therefore, the
free constructor with no parameters, which would have otherwise been generated is
not present. So, creating an instance of the zzz object by calling the constructor that
accepts no parameters, generate an error.

To summarize, when no constructors are present in the class, a constructor that does
not accept any parameters, is automatically generated. However, with the insertion
of even a single constructor, the free constructor is not created. In such a situation,
each and every new variant of the constructor has to be added manually.

a.vb
Class zzz
dim i as integer
Shared Sub Main
dim a as zzz
a = new zzz
a.i = 10
a.abc
a.pqr
End Sub
Sub abc
System.Console.WriteLine(i)
i = 20
End Sub
Sub pqr
System.Console.WriteLine(i)
End Sub
End Class

Output
10
20

The above example contains an instance variable i. It is referred to as an instance


variable since unlike 'a', it is not created in a sub, but is created outside the subs and
within the class.

The lifetime of an object such as 'a' endures as long as the sub is active; once the
sub concludes executing its code, all the variables that have been declared in it, lose
their values or are considered non-existent thereafter. The visibility of such variables
is restricted to the function or sub that they are created in. Thus, the object 'a' is
visible only within the sub Main and not in the other subs, such as abc.

On the other hand, the lifetime of the variable i is linked to the life-span of the
program. Since it is declared outside all the subs, it is visible in all the subs within the
class.

In main, the value of i is set to 10. It is prefaced with the name of the object, since it
is not shared. Then, the sub abc is summoned, which displays the value of 10 and
changes it to 20. Next, when the subroutine pqr is called, the value of the instance
variable is 20. This is for the reason that, only a single copy of i is created in memory,
when the zzz object is created. Thus, both the subs, viz. abc and pqr refer to this
same instance variable i.

a.vb
Class zzz
dim j as integer
shared dim k as integer
Shared Sub Main
dim a,b as zzz
a = new zzz(10)
a.abc(100)
b = new zzz(20)
b.abc(200)
End Sub
sub new(i as integer)
System.Console.WriteLine("in new {0} {1} {2}", i , j , k)
j=i
k=i
System.Console.WriteLine("in new {0} {1} {2}", i , j , k)
end sub
sub abc(p as integer)
System.Console.WriteLine("in abc {0} {1}", j , k)
k=p
j=p
end sub
End Class

Output
in new 10 0 0
in new 10 10 10
in abc 10 10
in new 20 0 100
in new 20 20 20
in abc 20 20

The above example reinforces the dissimilarities between a shared variable and a
non-shared variable. The words 'variable' and 'object' may be used interchangeably.
In the manner akin, what is pertinent to a sub is also applicable to a function, unless
otherwise specified.

In the above program, the class zzz has two variables:


• j - which is an instance variable.
• k - which is a shared variable.

The basic distinction between the two is as follows:


(a) A shared variable belongs to a class, which implies that each time a new
instance of the class is created, the shared variable does not get re-created. To
access the shared variable, the name of the class is used, since there is only a
single shared variable per class.

(b) An instance variable gets created, each time that a new instance of a class is
created. Therefore, if an object is instantiated on 20 counts, it will result in the
creation of 20 new copies of the instance variable in memory.

In Main, two local variables a and b, of type zzz are created. Since they are local,
they have a very short life span. While creating the object 'a', the constructor for the
object zzz is assigned a value of 10. Therefore, in the constructor, the value of i
becomes 10, whereas, both j and k have a value of 0. If the instance variables are not
explicitly initialised, the system initialises them to a value of zero.

The constructor assigns the value contained in i, i.e. 10, to both the variables j and k.
Therefore, in the second round, the WriteLine function displays the values of all three
variables as 10. The sub abc is then called with a parameter of 100. Here, the values
of variables j and k remain 10, as has been displayed by the WriteLine function. We
now re-initialize both the variables j and k to 100, and then, quit out of the sub.

The next statement in the Main function creates a new instance of zzz, wherein the
constructor is assigned a value of 20. The WriteLine function prints the values of i, j
and k as 20, 0 and 100, respectively. The instance variable j has a value of 0, as it
has been freshly created. Shared variables are not affected by the 'new' keyword.
Thus, the variable k retains its original value of 100, which was set in the abc
function. The second WriteLine function in the constructor displays the newly
assigned value of j and k, i.e. 20.

The abc function is called once again using the object b. The variable j now displays
the value of 20, since the constructor of the 'b' object in zzz had initialized it to 20.
This variable is then assigned a value of 200. However, the second copy of j, which
belongs to the object 'b', retains its value of 20, since it has nothing to do with the
variable j from the object 'a'.

To summarize what we have been harping on over and over, an instance variable
belongs to an object, whereas, a shared variable belongs to a class. This is
indubitably evident from the manner in which these variables are accessed. We are
taking the trouble of explaining all the above code and concepts, in order that you
can discern even the most diminutive of the Visual Basic .Net programs, generated
by Visual Studio.Net.

The approach that we have pursued is that we first explain the concepts using the
Visual Basic.Net compiler, and then we implement them in Visual Studio .Net.

Namespaces

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
a.abc
End Sub
End Class
Class yyy
sub abc
System.Console.WriteLine("abc")
end sub
end class

Output
abc

The above example lucidly establishes that a Visual Basic.Net program can contain
innumerable classes, as long as one of these classes contains the Sub of Main. The
above program has two classes named zzz and yyy. In the class zzz, 'a' is declared to
be an object of type yyy. After having created the object, the function abc is called
from it.
You may wonder as to what is the big deal here, since the program runs in a manner
akin to any other program. Although we accede to the fact that the program is no
different from the earlier ones, nonetheless, we would still like to forge ahead with it.

The class Console has a shared function called WriteLine, which is used to display
strings. So, nothing holds us back from creating a class called Console, in the fashion
similar to the one used to create the class yyy. Then, in the class, we can create our
own function named WriteLine.

This is perfectly within the realms of possibility, since we now know how to create a
class and a function within the class. However, there is bound to be some confusion
because when the user enters the statement 'Console.WriteLine', the framework
would be in a dilemma whether to call the function created by us or the one supplied
by Microsoft.

Microsoft seems to have already foreseen this predicament, and therefore, to avert
such name clashes from occurring, the big guys or Visual Basic.Net ordains that
every class should be a part of a name or a namespace. The next example
demonstrates the implementation of namespaces.

a.vb
Class zzz
Shared Sub Main
dim a as nnn.yyy
a = new nnn.yyy
a.abc
End Sub
End Class
Namespace nnn
Class yyy
sub abc
System.Console.WriteLine("abc")
end sub
end class
End Namespace

Output
abc

We have effected a minor amendment to the class yyy. A new word, i.e. Namespace
has been introduced above the class yyy, and the name assigned to it is 'nnn'. As a
rule, everything in Visual Basic.Net must terminate with the word End. Therefore, the
Namespace also ends with the words 'End Namespace'.

With the introduction of a namespace, the name of the class is no longer just yyy, but
is now 'nnn.yyy'. The syntax for the class name now changes to the following:
• name of the namespace followed by a dot, and finally, followed by the class
name.

Thus, whenever we need to refer to the class yyy, the reference to be employed is
nnn.yyy. If we omit the namespace 'nnn' from the DIM statement, the following error
is generated:

Error
c:\il\a.vb(3) : error BC30002: Type 'yyy' is not defined.

a.vb
Class zzz
Shared Sub Main
dim a as aaa.nnn.yyy
a = new aaa.nnn.yyy
a.abc
End Sub
End Class
Namespace aaa
Namespace nnn
Class yyy
sub abc
System.Console.WriteLine("abc")
end sub
end class
End Namespace
End Namespace

Output
abc

In the above example, two namespaces have been added to the class yyy, viz. aaa
and nnn. Thus, the name of the class now becomes aaa.nnn.yyy. The namespace
statement can be re-written as 'Namespace aaa.nnn'.

a.vb
Class zzz
Shared Sub Main
aaa.nnn.yyy.abc
End Sub
End Class
Namespace aaa.nnn
Class yyy
shared sub abc
System.Console.WriteLine("abc")
end sub
end class
End Namespace

Output
abc

In this example, the abc function is marked as 'shared'. Here, no object of type yyy
has been created. Thus, to call the abc function, the name of the class 'yyy.abc' is
used. Now, with the inclusion of the namespace tag above the class, the only way to
call this function is by using its full name, i.e. aaa.nnn.yyy.abc.

This syntax bears a resemblance to the commonly used System.Console.WriteLine.


Thus, a sub or a function has to be read from right to left as follows:
• The rightmost entity 'WriteLine' or 'abc' is the name of the method.
• The next entry on the left, i.e. 'Console' or 'yyy' is the name of the class.
• The next entry on the left, i.e. 'System' or 'nnn' is the name of the namespace
entity.
The Console class belongs to the System namespace. The WriteLine function is a
shared function in this class. In the case of methods that are not 'shared', the object
name has to be expressly specified to access the method.

Namespaces influence only the class names and not the object names. By employing
namespaces, both similar as well as disparate classes can be placed under a single
heading. Microsoft has politely reserved the use of the 'System' namespace. Thus, no
developer can ever create a namespace by that name, thereby avoiding any clashes
with Microsoft's set of entities.

Classes sharing the same names can be placed under different namespaces without
any confusion. However, the problem with using these namespaces is that they are
extremely lengthy. The next program provides a solution to this poser.
a.vb
Imports aaa.nnn
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
a.abc
End Sub
End Class
Namespace aaa.nnn
Class yyy
sub abc
System.Console.WriteLine("abc")
end sub
end class
End Namespace

Output
abc

The program begins with the newly introduced keyword of 'Imports', followed by the
name of the namespace, i.e. aaa.nnn. This statement does not introduce any new
code, as its sole task is to add the namespace aaa.nnn to every class, thereby
circumventing errors.

For instance, the Visual Basic.Net compiler would have thrown an error on
encountering the class yyy in the DIM statement, since there is no class called yyy.
However, on catching sight of the 'import' keyword, it adds the namespace to the
name of the class, resulting in the name aaa.nnn.yyy. As there already exists a class
by this name, the Visual Basic.Net compiler does not protest.

In case the error still persists, it takes the next set of Imports statement, and
attempts to seek a match. Only when all the Imports fail to find a match, a "not found
class" error is thrown. Effectively, the imports statement is like a short form, which
when introduced, eliminates the need for mentioning the namespace on every
occurrence of the class.

Bear in mind that it is the namespace, and not the name of the class, which is
permitted after the Imports keyword.

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
a.abc
a.pqr
End Sub
End Class
Class yyy
sub abc
System.Console.WriteLine("yyy abc")
end sub
end class
Class xxx
sub pqr
System.Console.WriteLine("xxx pqr")
end sub
end class

Error
c:\il\a.vb(6) : error BC30456: 'pqr' is not a member of 'yyy'.

The above example has three classes, viz. xxx, yyy and zzz. The class xxx has the
sub pqr, the class yyy has the sub abc, while the class zzz has the sub Main.

In Main, an object 'a' is created to be an instance of the class yyy. Thus, the sub abc
can now be called off it. However, calling the sub pqr using the object 'a' results in an
error, as the class yyy does not contain pqr. The class xxx contains the sub of pqr.
Thus, a class is a self-contained unit wherein, the entities belonging to one class
cannot be accessed by another class.

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
a.abc
a.pqr
End Sub
End Class
Class yyy
Inherits xxx
sub abc
System.Console.WriteLine("yyy abc")
end sub
end class
Class xxx
sub pqr
System.Console.WriteLine("xxx pqr")
end sub
end class

Output
yyy abc
xxx pqr

In the above program, we have merely added the word 'Inherits' to the name of a
class xxx, on the line below the class yyy. With this new induction, all the entities
present in the class xxx, now belong to the class yyy too. Thus, all the code and
instance variables that are present in the class xxx, can now be used by the yyy
object 'a'.

This is one of the most salient concepts in the world of object oriented programming,
wherein, a class such as yyy can derive itself from a base class like xxx. And by
virtue of this, it can reuse code that is present in this base class. Programmers are
very often mentally fine-tuned to write code in this fashion.
The code is never to be written from a scratch. Instead, it is derived from a class that
already has code present in it. By using 'inherits', the derived class simply inherits
everything from the base class.

Now, insert the following two lines on a single line as in.

Class yyy
Inherits xxx
to
Class yyy Inherits xxx

This action generates the following error:

Error
c:\il\a.vb(9) : error BC30205: End of statement expected.

Even though Visual Basic.Net is known to be an exceedingly flexible language, it still


requires us to adhere to certain rules. Thus, we have no choice but to place the word
'Inherits' on a separate line. The indentation is for the sake of neatness, and for good
luck of course!

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
End Sub
End Class
Class yyy
Inherits xxx
sub new
System.Console.WriteLine("new yyy")
end sub
end class
Class xxx
sub new
System.Console.WriteLine("new xxx")
end sub
end class

Output
new xxx
new yyy

In the above example, the class yyy derives from the base class xxx. Therefore, when
an instance of class yyy is created, two constructors are called, one from the class
xxx, and the other from the class yyy, in the prescribed sequence. This occurs
because the class yyy is also made up of the class xxx. Thus, while an instance of a
yyy object is being created, two objects are created in memory: a xxx object,
followed by a yyy object.

During the creation of these two objects in memory, the constructors of these classes
get called. A constructor, as you may recall, is called when an object is created. The
constructor of the base class, i.e. xxx is always called first, followed by the
constructor of the derived class yyy.

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
End Sub
End Class
Class yyy
Inherits xxx
sub new
mybase.New
System.Console.WriteLine("new yyy")
end sub
end class
Class xxx
sub new
System.Console.WriteLine("new xxx")
end sub
end class

Output
new xxx
new yyy

Yet another line has been added to the constructor of the class yyy, i.e. mybase.New.
Despite our not having created any variable or object called mybase, no error is
generated. This is because, every method or function or sub is provided with a free
object called mybase, which is a handle to the base class.

By specifying mybase.New, the constructor of the base class gets called. No specific
reason can be attributed to this, but most code written in the Visual Basic.Net world,
calls the constructor of the base class in the above-mentioned manner. The mybase
object is used to access members of the base class.

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
End Sub
End Class
Class yyy
dim i as integer
sub new
Me.i = 10
System.Console.WriteLine("new yyy {0}" , Me.i)
end sub
end class

Output
new yyy 10
Obtaining a free ride in life has never been too easy. In the Visual Basic.Net world,
not only do we get a free mybase object, but also acquire another object called Me.
The Me object is used to refer to itself, while the mybase object is used to refer to the
base class. In the above example, whether we write Me.i or i, it would mean the same
thing.

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy(100)
a.abc
End Sub
End Class
Class yyy
dim i as integer = 10
sub new(i as integer)
System.Console.WriteLine("new yyy {0} {1}" , Me.i , i)
Me.i = i
end sub
sub abc
System.Console.WriteLine("new yyy {0} {1}" , Me.i , i)
end sub
end class

Output
new yyy 10 100
new yyy 100 100

The utility of the reserved word Me is evident in the above example, where the class
yyy has an instance variable named i, and the parameter to the constructor is also
named i.

In the class zzz, 'a' is created as an object to yyy, by assigning a value of 100 to the
constructor. Doing so would load the yyy object in memory, where the first line is a
DIM statement. The DIM statement utilizes an 'equal to' sign to initialize the variable
during its creation. Thus, the instance variable i is initialized to the value of 10.

Thereafter, the constructor of class yyy is called, where the WriteLine function
displays the value of i. The i being referred to here is the parameter i in the
constructor, and not the instance variable i. This is because the parameters and local
variables get higher preference in a function.

However, using Me.i in the constructor would refer to the instance variable and not to
the parameter. The statement Me.i = i, would initialize the instance variable i to the
value stored in the parameter i. In the sub abc, i and Me.i will always refer to the
instance variable, since there is no parameter named i.

Thus, the keyword Me proves to be of great utility, when there is an instance variable
and a local variable, both having the same name.

a.vb
Class zzz
Shared Sub Main
dim a as yyy
a = new yyy
End Sub
End Class
Class yyy
Inherits xxx
sub new
mybase.New
System.Console.WriteLine("new yyy")
end sub
end class
Class xxx
Inherits ppp
sub new
System.Console.WriteLine("new xxx")
end sub
end class
Class ppp
sub new
System.Console.WriteLine("new ppp")
end sub
end class

Output
new ppp
new xxx
new yyy

In the above program, the class ppp is a self-contained unit, which is not derived
from any other class. Then, the class xxx is derived from class ppp. Hold your horses!
There is more to it. One more class yyy is then derived from the class xxx. As a
result, the class yyy is directly/indirectly derived from the two classes xxx and ppp.

Now, creating an instance of class yyy, would lead to the creation of three objects in
memory, viz. xxx, yyy and ppp. The sequence is important, since the base class
constructor always gets called first.

Thus, the ppp constructor gets called first, the xxx class gets called next, and finally,
it is the yyy class that gets called. The abovementioned rules apply, irrespective of
the number of classes that we derive from.

You might also like