You are on page 1of 31

Visual Studio Express:

Introduction to the Visual Basic


Programming Language
Author: Rich Tebb

Company: Content Master Ltd


Introduction
The Visual Studio Express Editions family provides a free, lightweight, and easy-to-learn
suite of programming tools that are aimed at the hobbyist, novice, and student
developer. Many people in this category will not have had any formal training in
computer science, and indeed they may not have any programming experience at all. If
you fall into this category, don’t worry – this guide is for you!
This beginner’s guide is designed for people with little or no prior knowledge of computer
languages, who want to learn to program by using the Visual Basic language. If you
have some previous programming experience, maybe in another language or from a few
years ago, then you may also find this guide useful. If you are a professional developer,
or you are already skilled in one or two programming languages, then you will probably
not have much to learn from this document.
Whether or not you have programmed before, you should already be familiar with
computers before reading this guide. It assumes that you can perform simple tasks like
starting a program, and that you are familiar with navigating around your computer by
using Windows Explorer.
So what will you learn by reading through this guide? Well, the most important thing you
can learn is that Programming is Fun! It’s a great feeling of satisfaction when you finish
a program and it does what you want – whether your program is a computer game that
you’ve invented, or it controls a robotic device, or serves any other purpose that you can
imagine. There may be obstacles along the way – like any challenge, programming can
present difficulties – but when you see your finished program working, you can take
pride in the fact that you overcame the problems, and converted your imagination into
reality.
As well as – we hope – learning that programming is fun, in this guide you will learn how
to create a simple program. Your program will include basic but essential programming
techniques such as methods, variables, controlling program flow, and how to create your
own classes – the fundamental structural units of a Visual Basic computer program.
Although you will be using Visual Studio tools to create your program, this is not a guide
to the full features of Visual Studio. You can learn more about how to use Visual Studio
in other MSDN guides.

What is Programming?
Contrary to popular belief, computers are not clever. Left to itself, a computer doesn’t
do anything at all – it won’t show the time, or display what you type on the screen, let
alone play a video game. The reason that computers are such useful tools, and give the
appearance of cleverness, is that they follow instructions, very accurately, very
repetitively, and very quickly. For example, when a computer displays a clock, it does so
because it has instructions for how to draw every color and tick mark in the clock face,
and every line in the clock’s rotating hands, onto the computer screen.
Programming is the act of giving instructions to a computer so that it knows how to
perform an action. Fundamentally, these instructions are a series of numbers – to a
computer, everything is numbers – in a kind of code where different numbers represent
different instructions. The good news is that programmers don’t have to learn all these
numbers (the ‘machine code’), because they can write their instructions in a more
intuitive form, and then have the computer convert these instructions into machine
code.
The intuitive or human-readable form of instructions is called a computer language. Like
languages in the real world, there are dozens of computer languages. Some are for
specialized tasks and others are more general-purpose. What all programming
languages have in common is that they enable programmers to create instructions for a
computer without having to learn the computer’s numeric machine code.
In this guide you will learn about Visual Basic, which is a general-purpose language that
you can use to program on the Microsoft .NET platform. You can program in Visual Basic
by using Visual Basic 2005 Express Edition, which is available as a free download
from the Microsoft Web site at http://msdn.microsoft.com/express/. The hands-on
examples in this guide assume that you have already downloaded and installed Visual
Basic 2005 Express Edition.

Lesson 1: Your First ‘Hello World’ Program


The first program that students traditionally write when they learn a new language is a
program that simply writes a message to the computer screen which reads “Hello,
world!” You can create a ‘Hello World’ program by following these instructions:
1. Open Visual Basic Express Edition – on the Start menu, point to All Programs, and
then click Microsoft Visual Basic 2005 Express Edition.
2. On the File menu, click New Project. In the Visual Studio installed templates
list, click Console Application, enter MyFirstApplication in the Name box, and
then click OK.
3. Visual Basic will create an outline program for you, and display the code for that
program in the code window.
4. Insert the following line of code (underlined below) into the outline program in the
code window:

Module Module1

Sub Main()

Console.WriteLine("Hello, world!")

End Sub

End Module
That’s it! You’ve just written your first program in Visual Basic. Let’s run the program to
see what happens.

Running the Program


Before you run the program, you should customize the Visual Basic 2005 Express Edition
menu so that the option that we use will be available. Take the following steps to
customize the menu:
1. On the Tools menu, click Customize.
2. Click to show the Commands tab.
3. In the Categories list, click Debug, then scroll the Commands list until you can
see the Start Without Debugging command.
4. Drag the Start Without Debugging command over the Debug menu, move the
insertion point below the Start / Continue command (as shown below), and then
release.

5. Click the Close button to dismiss the Customize dialog.

On the Debug menu, click Start Without Debugging (or just press Ctrl-F5). A
command prompt window appears that looks like this:
Press a key to dismiss the window.
The program you just wrote might not seem too exciting, but quite a few things
happened when you pressed Ctrl-F5.
1. Visual Studio detected that it needed to ‘build’ the program, because this is the first
time the program has been run.
2. To build the program, Visual Studio invoked a special kind of program called a
compiler, which understands the Visual Basic language and knows how to convert it
into machine code.
3. The compiler converted the ‘source code’ for your program (which is just a plain text
file containing the Visual Basic code you wrote) into machine code which the
computer can understand.
4. Once the compiler finished, Visual Studio took the compiler’s output – which is your
program – and ran that program. Because your program is a console application,
Visual Studio actually launched a console window and ran the program inside that
window.
5. Once your program had written “Hello, world!” on the screen and finished, Visual
Studio displayed the “Press any key” message so that you could see what your
program had displayed before the window closed.
You could do all these steps yourself, of course, but it’s much easier to use the Visual
Studio Integrated Development Environment (IDE) to do them on your behalf. However,
it’s important that you understand what’s going on behind the scenes.
Note The reason that you should use Start Without Debugging is so that the
Press any key to continue message is displayed after your program has finished
running. You can also use the Start Debugging menu option (or press F5) – as
shown on the video that accompanies this article – but then the console window is
closed as soon as your program has finished running, and you don’t get the chance
to read what’s displayed on the console.

A Closer Look at the Program Code


Now let’s examine the code and see how it works. Although you only added a single line
of code to the outline program that Visual Studio generated, the whole program code is
important so that the compiler can make sense of that single line.
All the code in the file is contained within two statements (shown below) that indicate
that we are creating a code module. A module is a general term for a file containing
code or information that you add to your project. Usually, a module contains program
code which you write. Along with classes (which you will learn more about shortly),
modules are the basic units of code in a Visual Basic program.
Modules and classes are containers for your code. You must have at least one module or
class in a program, but most programs have several. In the example below, everything
between the two statements is inside a module called Module1.

Module Module1

...

End Module

Inside the module there is a block of code called a subroutine. Modules and classes can
contain subroutines, but subroutines are the blocks of code that do much of the actual
work in a program. You use the Sub keyword to start a subroutine, and the End Sub
keyword to end it. Everything in between is part of the subroutine.

Sub Main()

...

End Sub

In this case, the program declares a subroutine called Main. We’ll take a deeper look at
subroutines later, but for now you need to know that the Main subroutine has a special
place in a program, because it’s usually where the program starts running. You can write
your subroutines in any order in the source code, but the Main method will be where
your program starts.
Inside the Main subroutine, we have the code which actually writes the message to the
screen:

Console.WriteLine("Hello, world!")

In this case, we use a class called System.Console, which is part of the .NET
Framework. Inside the System.Console class there is a subroutine called WriteLine,
which writes a message to the console screen (“Write”) and skips to the next line
(“Line”).
As an aside – how is it that the class is called
System.Console but we just call it Console
in our program? Well, Visual Basic
enables you to use abbreviations if you
use certain classes regularly. In this
case, the Console class is part of a
group of classes in a namespace called System. A namespace is a way of grouping
several classes or modules together.
The diagram shows the structure of the System namespace, and how it contains many
classes. Because the System namespace contains commonly used classes, Visual Basic
automatically creates the abbreviation for you, so that you only need to type the name
of the class and not the full name including the namespace.

Lesson 2: Using Methods and Variables


As you saw above, all programs must define a subroutine called Main, which is the
starting point for the program. But you can also add other subroutines. Usually you
would create a subroutine when you want to perform the same set of instructions,
perhaps with slight differences, several times in a program.

The SayHelloWorld Subroutine


Let’s have a look at how you would create a subroutine. In the source window, right
after the End Sub of the Main subroutine, add a newline and then add the following code
underlined below:

Module Module1

Sub Main()

Console.WriteLine("Hello, world!")

End Sub

Sub SayHelloWorld()

Console.WriteLine("Hello, world!")

End Sub

End Module

You can see that the SayHelloWorld subroutine has some similarities with the Main
subroutine. In fact, apart from their names, the Main subroutine and the SayHelloWorld
subroutine are identical – they both call Console.WriteLine. Let’s see how the
SayHelloWorld subroutine works in action. Modify the Main subroutine so that it calls
the SayHelloWorld subroutine instead of calling Console.WriteLine, as follows:
1. In the Main subroutine, delete the line that reads
Console.WriteLine("Hello, world!")

2. Add a line that reads

SayHelloWorld()

Now run the program without debugging (Ctrl-F5). There’s no visible change between
the output of the original program and the new version. The only difference is that the
Main subroutine no longer writes to the console itself; it calls a different subroutine to
write to the console on its behalf.

The SayHelloTo Subroutine


The SayHelloWorld subroutine doesn’t add much to your program – it’s just a way of
illustrating how you can create and call a subroutine. Now let’s create a different
subroutine, a bit more useful this time because it’s slightly more flexible.
Add the following code underlined below, right after the SayHelloWorld subroutine:

Module Module1

Sub Main()

SayHelloWorld()

End Sub

Sub SayHelloWorld()

Console.WriteLine("Hello, world!")

End Sub

Sub SayHelloTo(ByVal toWhom As String)

Dim message As String

message = "Hello, " & toWhom

Console.WriteLine(message)

End Sub
End Module

You can see the obvious similarities between this subroutine and the SayHelloWorld
subroutine. But there are some interesting differences, too. Before we examine them,
let’s see this subroutine in action. Modify the Main subroutine by adding the following
lines right after the line that calls SayHelloWorld:

SayHelloTo("Eric")

SayHelloTo("Sandra")

Run the program without debugging. You should see the following output:

You can probably see the gist of what’s going on here. The SayHelloTo subroutine
allows you to specify to whom to say hello, by putting the name of the person as a
parameter when you call the subroutine (you can think of a parameter as an input to a
subroutine). We put parenthesis “(” and “)” around the parameters after the subroutine
name.

Within the SayHelloTo subroutine, we don’t know what the actual value of the
parameter will be when someone calls the subroutine. In this program, the values “Eric”
and “Sandra” are used; but you could use other values instead. The SayHelloTo
subroutine needs a way of handling the value without knowing what the value actually
is. To get round this, Visual Basic enables us to create a ‘slot’ for the value, and give
that slot a name. In this subroutine, we’ve called the slot toWhom. The proper term for
the slot is a variable, so called because the slot’s value can vary. Don’t worry too much
about the other details of this subroutine for now – we’ll revisit them further on.

Variables and Data Types


Variables are very important features in Visual Basic, or any other programming
language. A variable is where you can store information and retrieve it (in computer
terms, a variable refers to an area of computer memory where the variable’s value is
stored). You must give the variable a name, which you then use when storing or
retrieving information from that variable. The name you use for a variable can be
anything that you choose, subject to a few restrictions:
• Variable names can only contain letters, numbers, and the underscore ‘_’ character.
They cannot contain spaces or punctuation.
• Variable names cannot start with a number.
• Variable names must not clash with other variable names – you cannot use a
variable name if it’s already in use in the same part of the program (this restriction
isn’t as severe as it may seem, for reasons that will become apparent).
To help the computer set aside the right amount of memory for the variable, Visual
Basic requires that you specify a data type in addition to the variable name. A data
type, as the name implies, denotes what type of data the variable will hold. There are
many different data types in Visual Basic, and you can create your own; but some
examples of the most commonly-used types are:

Data type Description Example

Integer An integer, 4 bytes in size, which can 43


hold a value between -2,147,483,648
and 2,147,483,647
Byte An integer, 1 byte in size, which can 127
hold a value between 0 and 255
Decimal A number with decimal places, which 10966.2592
can hold a value between ±1.0×10-28
and ±7.9×1028
String A sequence (or “string”) of characters "Hello, world!"
Char A single character 'h'
Boolean A logical value which can be either True True
or False

Before you can use a variable, Visual Basic insists that you declare it1. This means that
you must specify the type and the name of the variable, so that the program knows
what you are talking about before you start to use it. A declaration can be a simple
statement such as

Dim x As Integer

This declares a variable called x which will contain values of integer type. You can
optionally assign a value to the new variable when you declare it, as follows:

Dim y As Integer = 43

This statement declares a variable called y, as above, and then initializes it with a value
of 43.
Visual Basic imposes an important restriction on your use of variables. It does not allow
you to store a value that has one data type in a variable of a different data type. This
can be a little confusing at first, because you can’t do some things that seem perfectly
obvious. For example, here is some code that declares two variables and assigns values
to those variables.

Dim myInteger As Integer = 43;

Dim myString As String = "43";

It might seem obvious that myInteger and myString have the same value, but to the
computer these variables have completely different values. In fact, they have completely
different types, so you couldn’t even compare myInteger and myString to see if they
were the same value! myInteger can only contain values of type Integer, while
myString can only contain values of type String. So even though 43 is an integer value,
when we put quotes ("") around it, Visual Basic treats whatever is between the quotes
as a String value.
Visual Basic does have one trick up its sleeve, however. If you assign a variable with one
data type to a variable with another data type, Visual Basic will try to convert the right-
hand value to the correct data type to match the left-hand variable. If successful, the
program will continue. The problem is that sometimes the conversion won’t succeed,
and when that happens, your program can’t continue.

1
In fact, you can configure Visual Basic so that it doesn’t insist that you specify a data
type. However, this feature is really just for backwards compatibility with older
programs, and you should never need to set this up.
Let’s have a look what happens when you try to mix data types. Create a new method in
the program by adding the following code after the SayHelloTo method:

Sub Wrong()

Dim myInteger As Integer

Dim myString As String = "43"

myInteger = myString

Console.WriteLine(myInteger)

myString = "Banjo"

myInteger = myString

Console.WriteLine(myInteger)

End Sub

This method attempts to assign a string value (myString) to an integer variable


(myInteger), with different values in myString. The first time, myString contains a
string that can be converted to a number, so Visual Basic converts the string to an
integer and assigns that value to myInteger. On the second occasion, myString contains
the value "Banjo" which can’t be converted to a number. When the program runs, this
conversion will fail and the program will stop running. The following steps show what
happens when you try:
1. Add the following line of code (underlined) into the Main subroutine:

Sub Main()

SayHelloWorld()

SayHelloTo("Eric")

SayHelloTo("Sandra")

Wrong()

End Sub

2. Press Ctrl-F5 to run the program without debugging.


3. At first, a few lines appear on the console as usual:

4. Then, a dialog box appears that indicates a problem (your dialog box may look
slightly different than this):

5. Click the red X at the top right to dismiss the dialog box. Finally, several messages
are displayed in the console, which provide details about the error that occurred.
Press any key to close the console window.
You can ignore most of the error text for the time being; but notice that the first line of
the error message states:
Conversion from string "Banjo" to type 'Integer' is not valid.
This is our clue as to what has happened to cause this error. The message tells us that
the conversion is not valid – which is not surprising, because "Banjo" isn’t a number!
If you examine the entire console output, you can glean some more information by
seeing how much of the program worked successfully before the error occurred. In this
case, you can see the number 43 printed right before the error text. It’s a pretty good
bet that the first Console.WriteLine statement inside the Wrong subroutine printed this
number – so we can assume that the first conversion, from the string "43" to an integer,
was successful.
The moral of this tale is that you need to be careful when you mix data types, because
your program can fall over while it’s running if you get things wrong. The simplest rule
of thumb is that you should never assign variables from one data type to another
without performing a conversion first – don’t rely on it happening automatically!
Now you have seen what happens when you try to mix data types, you should delete the
Wrong method from the program, and delete the line in Main that calls Wrong. Run the
program again to check that it works correctly.

The SayHelloTo Method Revisited


Now you understand what a variable is, let’s take another look at the SayHelloTo
subroutine to get a deeper understanding of how it works.

Sub SayHelloTo(ByVal toWhom As String)

Dim message As String

message = "Hello, " & toWhom

Console.WriteLine(message)

End Sub

The first line is the subroutine header, and tells us the name of the subroutine, along
with what parameters it expects a caller to provide. In this case, the SayHelloTo
method expects a parameter with a string type (“As String)”), which is identified by
the name toWhom. ByVal is a special keyword that only appears in parameter lists – you
can ignore it for the time being2.

2
The ByVal keyword actually specifies that the value of the variable underlying the
parameter is not changed by the subroutine. If you omit this keyword, and you make a
change to the value of the parameter variable inside your subroutine, then your
subroutine will change the value of the variable that was passed in to the subroutine.
The first statement in the method body declares another string variable, called message.
The Dim keyword3 lets the computer know that you are about to declare a variable. If
you are declaring more than 1 variable, it is good form to put all your Dim statements at
the beginning of the subroutine in which you will use these variables.
The second statement assigns a value to the message variable that consists of the string
"Hello, " joined to the value of the toWhom variable. The ampersand sign “&” operator is
used to append string values together. So if the caller of the method passes a parameter
of "Eric" when it calls SayHelloTo, then the variable message will have a value of "Hello,
Eric" after this statement has executed.
The third statement is our old friend Console.WriteLine. There is a subtle difference
here from how we’ve used it previously, however. Notice that there are no quotation
marks around message. This is because we are passing the value inside the message
variable, not the actual string "message", as a parameter to the Console.WriteLine
method.
To see the effect of this subtle but important difference, change the second statement so
that it reads Console.WriteLine("message") - including the quotation marks - and run
the program again without debugging. This time, the output from the SayHelloTo
method is not what we intended:

Because of the enclosing quotation marks, the compiler has used the literal string
"message" instead of the value of the message variable as a parameter to
Console.WriteLine. We don’t want SayHelloTo to work like this, so go ahead and
remove the quotes around message, then run the program to check it’s working
correctly.

Functions - Subroutines That Produce


Output Values
So far, the subroutines you have written simply perform some actions on behalf of your
program. By using variables and parameters, a subroutine can perform the same action
with different data. But you can also write methods that calculate a value and send that
value back to the caller – these are called functions. The main difference between
subroutines and functions is that functions must return an output value.
You can think of a method as an action or set of actions grouped together. So, when you
brush your teeth in the morning, you can think of the ‘Brushing Teeth Procedure’ as a
method. We talk about 2 types of methods in this guide: Subroutines and Functions.
Both of these types of methods may take an input (toothbrush, toothpaste, teeth), and

3
The Dim keyword is an abbreviation of the word ‘Dimension.’ The name refers to the
size (or dimension) of the space in memory that is set aside for the variable.
do something with the input (brush teeth). The main difference between Subroutines
and Functions is that a Function has an Output value as well. So the ‘Brushing Teeth’
method may be a Subroutine, and a ‘Make Toast’ method may be a Function since the
input is bread, and the output is toast.
Add the following code right after the SayHelloTo subroutine:

Function CalculateGreeting(ByVal toWhom As String) As String

Dim message As String = "Hello, " & toWhom

Return message

End Function

There are two important differences between this function and the SayHelloTo
subroutine. The first is in the header – instead of saying Sub it says Function. This tells
the compiler that CalculateGreeting produces an output value. The last part of the
header (underlined below) tells the compiler that the output from CalculateGreeting
has a String data type.

Function CalculateGreeting(ByVal toWhom As String) As String

The other difference is in the last statement in the function, which reads

Return message

The Return keyword indicates the value that the function should return to the caller – in
this case, the value to return is the contents of the message variable. The value returned
by a function is called the return value or result.
What the CalculateGreeting function does is to perform a calculation, and then send
the result of the calculation back to the code that called the function.
Now modify the second statement in the SayHelloTo subroutine as underlined below, so
that it reads:

Sub SayHelloTo(ByVal toWhom As String)

Dim message As String

message = CalculateGreeting(toWhom)

Console.WriteLine(message)

End Sub

The added expression is a function call, which works like when you called the
SayHelloTo subroutine from the Main subroutine. The difference is that, with this
function, the program takes the result of CalculateGreeting and assigns that value to
the message variable. Run the program to check that it works, and that you still see the
same console output as before.

Lesson 3: Controlling Program Flow


So far, our program has operated in a straightforward sequential manner. The program
starts executing in the Main subroutine, and proceeds until the end of that subroutine,
with a couple of diversions into other methods (the generic term for subroutines and
functions) along the way. Those methods, in turn, simply start on the first statement of
the method, and carry out every statement until they reach the end of the method.
When each method ends, the program returns to the piece of code that called that
method; and when the Main subroutine ends, the program ends.

Conditional Behavior and Expressions


But what if we want to make the program behave in a slightly different way under
certain conditions? This is known as conditional behavior, because the behavior of the
program depends on specific conditions being met when the program is running – “if this
condition is true, then do this, else do that”. As an example, let’s change the
CalculateGreeting function so that it gives a different greeting message depending on
the person whom it is greeting. Replace the existing CalculateGreeting function with
the following code:

Function CalculateGreeting(ByVal toWhom As String) As String

Dim message As String

If toWhom = "Eric" Then

message = "Hi, " & toWhom

Else

message = "Hello, " & toWhom

End If

Return message

End Function

In this version of the CalculateGreeting method, we use an If statement to test the


value of toWhom. If the value of toWhom is equal to "Eric" then the method returns one
greeting, otherwise it returns a different greeting. By now it will be easy for you to guess
what the output will be when you run the program:

In the If statement, the program compares the value of the toWhom variable against the
string "Eric". This uses the equality operator, and you use it when you want to test
two values to see if they are equal. There are a few other comparison operators in Visual
Basic:

Operator Description

= Equality. The expression has the value True when the left hand and
right hand values are equal, False otherwise.
<> Inequality. The expression has the value True when the left hand
and right hand values are not equal, False otherwise.
< Less than. The expression has the value True when the left hand
value is less than the right hand value, False otherwise.
> Greater than. The expression has the value True when the left hand
value is greater than the right hand value, False otherwise.
<= Less than or equal. The expression has the value True when the left
hand value is less than or equal to the right hand value, False
otherwise.
>= Greater than or equal. The expression has the value True when the
left hand value is greater than or equal to the right hand value,
False otherwise.

Let’s just pick up on a point there. What exactly does “the expression has the value
true” mean? Well, to use the example from the CalculateGreeting function, the
underlined part is the expression:

If toWhom = "Eric" Then

When the program runs, the expression is evaluated (this is a computer-speak term for
‘worked out’) and the result determines which of the following code blocks is executed.
If the toWhom variable has the value "Eric", then the expression toWhom = "Eric"
evaluates to True. In this case, the program executes the code block following the If. If
toWhom has some other value, then the expression evaluates to False, and the program
skips the If code block, and executes the code block following the Else. In Visual Basic,
you don’t actually need to provide an Else section. If you omit this section, then the
program will continue execution after the If code block.
These kinds of expressions that evaluate either to True or to False are called Boolean
expressions. They are very common in computer programming, which is why they
have a special word to describe them. The Boolean data type, introduced above, holds
Boolean values.

Looping and Iteration


Part of the power of computers is that they can perform tasks repetitively, and for that
we need a way of telling our program to repeat itself. The technical term for this
repetitive behavior is looping. A loop is a series of instructions that is repeated until a
certain condition is met. Usually a loop contains a Boolean expression that determines
whether to continue looping or to stop.
Let’s look at an example of a loop. We will change the program so that it repeatedly
asks for a person’s name, and then displays a greeting, until someone just presses the
Enter key. Modify the Main method so that it looks like this:

Sub Main()

Console.Write("Please enter your name: ")

Dim name As String = Console.ReadLine()

While name <> ""

SayHelloTo(name)

Console.Write("Please enter your name: ")

name = Console.ReadLine()

End While

End Sub

Run the program. When prompted, enter a name and press Enter – you can try this as
many times as you like. When you get bored, just press Enter without typing a name.
Depending on how quickly you get bored, the output will look something like this:
The first point about our new Main method is that it uses two methods that we haven’t
used before: Console.Write and Console.ReadLine. Console.Write is almost identical
to Console.WriteLine, except that it doesn’t add a line break after it has written the
text. Console.ReadLine is a somewhat new concept, because it reads from the console
rather than writing to it. When your program calls Console.ReadLine, the program
pauses until the user presses the Enter key. The return value from Console.ReadLine is
a string containing the text that the user typed before pressing Enter.

The important change in the Main method is the use of the while loop. This is how the
while loop works:
1. At the start of the loop, the program evaluates the While condition, which is a
Boolean expression like the ones you have already seen. Literally translated, this line
would read “While the value of the variable name does not equal "" (blank), do the
following”
2. If the condition is true, then the code block is executed, otherwise the program skips
over the code block and continues from there.
3. When all the statements in the code block have executed, the program loops back to
the top of the While statement and evaluates the conditional expression again.
Notice that we had to initialize (set the value of) the variable name before we entered
into our While loop in order to be able to evaluate the Boolean expression. In our loop,
the conditional expression will be false once the user presses Enter without typing
anything else. In this case, the return value from Console.ReadLine is an empty string,
which is represented in Visual Basic by two double-quotes with nothing in between. Once
this happens, the program skips over the code block and continues with the next
statement.
In summary, a While loop repeats while an expression continues to be true. The loop
will exit the first time the expression evaluates to False.

The For … Next Loop


The While loop is useful when you want to repeat a code block for an uncertain number
of times. What about when you already know how many times you want to repeat the
code block? The tool of choice in this situation is the For ... Next loop, which you use
to repeat the loop for a certain number of times.
Let’s say that we want our program to greet three people only, no more and no less.
Here’s how you should modify the Main method to loop three times:
Sub Main()

Dim i As Integer

For i = 1 To 3

Console.Write("Please enter your name: ")

Dim name As String = Console.ReadLine()

SayHelloTo(name)

Next

End Sub

The For ... Next loop looks a little more complex than the While loop, because there
are a few things going on under the hood. The diagram shows the parts of a For ...
Next clause, using the example above. Here’s how it works:

1. The For expression sets the counter variable i to the start value, which is 1 in our
example. Visual Basic then tests that the counter variable is less than or equal to the
end value, which is 3 in this example.
2. If the start value is less than or equal to the end value, then Visual Basic executes
the code block inside the loop.
3. When the program reaches the Next statement, Visual Basic automatically adds 1 to
the counter variable i. The Next keyword automatically increments the For loop
counter variable for you.
4. The program then goes back to the For statement, and continues as in step 1 by
checking whether the counter variable is less than or equal to the end value. If so, it
processes the code block again. When the counter variable is greater than the end
value, the program continues with the statement after the Next statement.
Looping the right number of times can be confusing – even for experienced
programmers! Let’s walk through the example and see how it ensures we only execute
the code block three times. Focus on the counter variable (i), and how its value changes
each time through the loop. The table below shows the value of the variable i each time
the For statement checks to see if it should continue:

Value of i Notes

1 On the first pass through the loop, the For statement has just assigned
the start value (1) to the counter variable (i). The counter variable is
less than the end value (3), therefore the loop goes on to execute the
code block.
2 The next time the condition is evaluated, the main code block has been
executed and the Next statement has added 1 to the value of i. The
counter variable i has the value 2, which is less than the end value, so
the loop continues.
3 On the next occasion that the condition is evaluated, the main code block
has by now been executed twice. This time, the counter variable is equal
to the end value; this still means that the loop can continue.
4 On the next pass, the main code block has been executed three times in
total. This time, i has the value 4, which is greater than the end value,
so the loop ends.

You can use different start and end values in the loop. In the above example, we could
achieve the same result if we used a start value of 33 and an end value of 35 – the loop
would still execute exactly three times.

Lesson 4: Creating Your Own Classes


Way back when we looked at the original Hello World program, you may remember that
the outline code created by Visual Studio looked like this:

Module Module1

...

[the program code goes here]

...

End Module

At that point, we mentioned the concept of classes by saying that they, like modules,
are a container for code. Classes are more than this, however – they are fundamental to
programming in Visual Basic, because they enable you to organize your code in a
sensible way. Just as, in a museum, the curators group related items together and
display them in the same room; in the same way, you can use classes to group together
related parts of your code. The reason in both cases is the same – so you can find your
way around. In a small program like our Hello World program – just like in a small
museum – you can find what you want just by looking through everything, even if there
is no organization. But as you write bigger and more complex programs, you will find
that the way you organize your code helps you to find what you want. So it is important
to understand how you can add structure to your programs by using classes.

The Greeting Class


Although classes can help you to structure your program, there is no right or wrong way
to do so. To use the museum analogy, a curator might choose to organize the collection
in chronological order, or by the type of artwork – paintings in one area, sculptures in
another – or even alphabetically. Some ways of organization are perhaps more useful
than others, and many books have been written on how best to organize a program, but
ultimately the decision is with the design team.
This guide does not attempt to discuss program design; but you can learn how to create
and use classes in Visual Basic. In this section, you will create a class that manages
greetings, which will replace the SayHelloTo method that you wrote earlier. To create

the Greeting class, use the following steps:


1. In Visual Studio, in the Solution Explorer window, right-click the MyFirstApplication
project, point at Add, and then click Class.

2. In the Name box, type Greeting.vb, and click Add.


Visual Studio creates a new file called Greeting.vb, with the outline code for the Greeting
class, which looks like this:

Public Class Greeting

End Class

Except for the absence of a Main subroutine, this is remarkably similar to our original
Module1 module. We have defined a class called Greeting, although it has no contents
at the moment. To rectify that, modify the Greeting class so that it looks like this:

Public Class Greeting

Private _recipient As String

Public Sub New()

_recipient = "Stranger"

End Sub

Public Sub Display()

Dim message As String = "Hello, " & _recipient

Console.WriteLine(message)

End Sub

Public Property Recipient() As String

Get

Return _recipient

End Get

Set(ByVal value As String)


_recipient = value

End Set

End Property

End Class

Before we examine the Greeting class in detail, let’s see it in action. Go back to the
Module1 module (click on the Module1.vb tab at the top of the code window), and
modify the Main subroutine as follows:

Sub Main()

Dim theGreeting As Greeting

theGreeting = New Greeting

theGreeting.Recipient = "Eric"

theGreeting.Display()

End Sub

Now run the program without debugging. The output looks like this:

In terms of what the program does, there’s not much change here from what we’ve seen
before. In terms of how the program does it, however, this is a whole new ball game.

Using the Greeting Class


Before we examine the Greeting class itself, let’s take a look through our new Main
subroutine in the Module1 module. The way that we use the Greeting class introduces
some important new concepts.

Dim theGreeting As Greeting

The first statement declares a variable called theGreeting, much like we saw earlier.
The difference between this declaration and the ones we saw earlier is that the type of
the variable is Greeting, rather than Integer or String. As you learned earlier, this
means that the variable ‘slot’ can only hold a Greeting value. The slot is initially empty,
so the next line puts something in the slot:

theGreeting = New Greeting

This statement creates a new Greeting object and stores it in the theGreeting variable.
What this means, and why you must do this, requires a bit of background explanation.
When you defined the Greeting class in Greeting.vb, you did not actually create a
specific Greeting object. The class definition simply describes a conceptual Greeting.
You can think of a class as a blueprint for a house, and an object as the house itself. If
you like, it tells the compiler “I am defining a class of objects in my program, called
Greeting; and this is what a Greeting object would look like and how it would behave.”
To use one of these Greeting objects, you must create a new object based on the
Greeting blueprint or class. This new object is an instance of the Greeting class, and
the process of creating the object is called instantiation. In Visual Basic, you use the
New keyword to instantiate a class.

theGreeting.Recipient = "Eric"

Now we have created a Greeting object, we can start to use it. As you will see below,
we have defined a property of the Greeting class called Recipient. The Recipient
property represents the recipient of the greeting. In this case, we want to greet Eric, so
we set the Recipient property accordingly.

theGreeting.Display()
This statement calls the Display subroutine on the theGreeting object to display the
greeting on the console. The Display subroutine is also defined in the Greeting class.

A Closer Look at Greeting


Now we know how a Greeting is used, let’s take a step by step look through the
Greeting class.

Public Class Greeting

Private _recipient As String

The above line declares a variable called _recipient. Note that the variable declaration
exists outside of any method. This means that the variable belongs to the class as a
whole, rather than to any one method. A variable declared at class level is called a
member variable.
The keyword Private refers to the access level of the member variable. By declaring
the variable as Private, this prevents any external code from viewing or changing the
variable – effectively, the variable is hidden from any code that isn’t part of the
Greeting class. It is good practice to declare all member variables as private – in fact,
you should hide any of the ‘inner workings’ of your classes by making them private. This
helps each class to be a ‘black box.’ You will see the advantage of this later on.
In case you were wondering, the underscore character ‘_’ at the start of the variable
name has no special significance in Visual Basic. It is merely a naming convention, used
to indicate that _recipient is a member variable.

Public Sub New()

_recipient = "Stranger"

End Sub

The next section of code declares a subroutine called New. Sub New is a special case – it
is called a constructor, and it is used to create a new instance of the class, as the
name implies, when the New keyword has been used.
Just now you saw how we declared the _recipient member variable as private to hide
it from any code outside of the Greeting class. In contrast with the variable, we have
declared the constructor as public, which means that code outside of the Greeting
class can call it. Constructors are usually public, otherwise it would not be possible for
outside code to create an instance of the class! In Visual Basic, you don’t need to use
the Public keyword, because that is the default access level for class members.
However, it is good practice to always indicate the access level
In the Greeting constructor, the only action is to initialize the _recipient member
variable to a default value. In this case, the default value is "Stranger".
Public Sub Display()

Dim message As String = "Hello, " & _recipient

Console.WriteLine(message)

End Sub

The Display method is an ordinary method like those we have seen before. It creates a
message based on the recipient’s name and writes the message to the console.

Public Property Recipient() As String

Get

Return _recipient

End Get

Set(ByVal value As String)

_recipient = value

End Set

End Property

The last section defines the Recipient property. A property is a member of a class that
provides access to data in that class in a controlled manner. In this case, the Recipient
property provides access to the _recipient member variable without the need to make
_recipient public.
What’s the deal here? Why not just make the member variable _recipient public, and
do away with the Recipient property? To understand the answer, you first need to
understand how properties work.
A property has a type, just like a variable – in the case of the Recipient property, its
type is String. A property also has get and set accessors, which are somewhat like
methods and are represented in Visual Basic by the Get ... End Get and Set ... End
Set constructs. These accessors provide access to the property itself. Remember this
statement in Program.Main:

theGreeting.Recipient = "Eric"

This statement sets the Recipient property to have the value "Eric". Behind the scenes,
this calls the set accessor in the Greeting class. The set accessor looks like this:

Set(ByVal value As String)


_recipient = value

End Set

For the set accessor, there is a pre-defined parameter named value that holds the value
being assigned to the property. In this case, that value is stored in the _recipient
member variable.
The get accessor works in the opposite way. If the Program.Main method included a line
such as this:

Console.WriteLine(theGreeting.Recipient)

then the program would write "Eric" on the console. The get accessor returns the value
of the _recipient member variable.
Let’s go back to the earlier question – why go to all the trouble of defining a property
that has the same effect as making _recipient public? The answer is that, by using the
code inside the get and set accessors, you can control access to the _recipient
member variable.
Why would you want this control? Imagine that, at some future point, you want to
prevent the Recipient property from having a certain value (such as an empty string).
By adding some code to the set accessor, you can prevent the caller from assigning this
value to _recipient. Without the property accessor methods, you would have to check
every single time any code, anywhere in your program, wrote a value to the _recipient
member variable.
The use of properties to control access to class data is an example of a concept called
encapsulation. If you remember back to the explanation of what classes are for, you
learned that they add structure to a program by bringing together all the code that
relates to a certain part of the program. As an example of this, by encapsulating the
_recipient member variable inside a property, you have brought all the code that
controls the value of _recipient into a single location, instead of the code being
scattered all around your program. As your programs get bigger, you will find them
much easier to manage when you can design them so that related code is organized in
one place.

Summary
This guide ends just as you have met the fascinating subject of program design, by
building your first class. Along the way, you have learned about methods, data types,
variables, and controlling program flow with conditionals and loops. These are the basic
building blocks of any program. Once you have mastered these tools, you are well on
your way to becoming a fully-fledged programmer.
If you have enjoyed learning how to make a program work, there are many
opportunities for you to take your next steps. This guide has only introduced some of
the more common building blocks, and there are several more for you to discover.
Now that you have learned the basics of the Visual Basic programming language, here
are some other concepts to learn about on your own:
• Using other loops and conditionals. You have seen the most commonly-used
loops and conditionals in this guide. You can also learn about Do loops, For Each
loops, and Case statements.
• Exploring the .NET Framework. Your first program used only the Console
framework class. There are hundreds of classes in the .NET framework that enable
you to do anything from networking with other computers to creating 3-dimensional
games.
• Using arrays and collections. Arrays and collections enable you to work with
groups of objects rather than defining an individual variable for each one.
• Handling exceptions. A program causes an exception when it does something that
it shouldn’t, like dividing by zero. Good programs are prepared for the unexpected,
and can receive notifications of these exceptions so they can take appropriate action.
• Inheritance, interfaces and polymorphism. When you create a class, you can
inherit the behavior of an existing class so that your own class behaves in a similar
way. You can also use interfaces to define what methods and properties a class
should have, so that several different classes can have the same appearance.
• Using Generics. Generics enable you to write ‘generic’ classes, such as collection
classes, that can ensure that you don’t put the wrong type of object into a collection.
The MSDN Web site has many more lessons for you to study as you progress to more
advanced techniques and more complex programs. Happy learning!

You might also like