CH04 NutsBolts
CH04 NutsBolts
CH04 NutsBolts
The files associated with this chapter are located in the following directories:
○ VB.NET\NutsBolts
○ VB.NETLabs\NutsBoltsLab
○ VB.NETLabs\NutsBoltsLabCompleted
Open a Command Prompt window and type vbc. You will see all of the
switches and options for the command line compiler, as shown in Figure 1.
Figure 1. The Command window displays the switches for the command line
compiler.
We’re not going to cover all of the compiler options beyond creating a basic
Hello World console applicationyou can explore these for yourself by
simply reading the output shown in Figure 1. If you need a complete listing
with more detailed information than you see in the Command Prompt window,
you can search the online Help for “compiler options.”
Once you’ve configured the compiler, you can create a simple application.
You can create the following types of applications:
TIP: If working with Notepad and the Command Prompt window is not your cup
of tea, you can simply use Visual Studio .NET to create and compile all these
types of applications, and that’s what the bulk of this course focuses on.
Key Terms
Try It Out!
Follow these steps to build a simple Hello World console application with
Notepad and vbc.exe:
Note that comments in Visual Basic .NET start with a single quote
character and are ignored by the compiler. The single line of code in
the application, the WriteLine method, works because the
System.Console reference tells the compiler where to look for the
WriteLine method. The classes in the System namespace are found in
the mscorlib.dll, which is the big enchilada of the .NET Framework.
You’ll learn more about namespaces and base classes later in the
course, but for now it’s enough to know that this is what makes the
code happen when you compile and run it.
c:\HelloWorld.vb
vbc HelloWorld.vb
TIP: Most of the options on the Start Page can also be found on the main File
menu.
Figure 4 shows the Start page with the Find Samples tab selected. You can
search on any keyword and a list of relevant topics will be displayed.
Figure 4. The Find Samples tab lets you search for code samples based on the
language you are programming in.
Click the My Profile link displayed in the lower left-hand corner of Figure 4.
This takes you to the Profile page, where you configure options shown in
Figure 5.
Figure 5. The My Profile link lets you configure your profile for Visual Studio
.NET.
The profile you select will reflect your comfort levelhere are the options you
can choose from:
This courseware is based on the Visual Basic Developer option, which will
give you all of the same shortcut keys that you are already familiar with if you
are a Visual Basic 6 programmer migrating to .NET. If you choose one of the
other options, some of the instructions you may see in other chapters will not
work.
See NutsBolts.sln When you create a Windows application, you will see the project listed in the
Solution Explorer shown in Figure 6. A solution can contain one or more
projects, although in this case it only contains one, NutsBolts.
When you save your project, the files are saved separately to disk, as shown in
Figure 7. The solution file, or NutsBolts.sln, is used to load the other files that
comprise the solution. Note that all code, whether in a form or a module, is
saved in a file with a .vb extension.
Project Properties
The Project Properties dialog box provides settings that are configurable at the
project level. Unlike your profile, which applies to all of Visual Studio .NET,
project properties apply only to the project they are set for.
For a Windows project, you need to designate either a startup form (frmMain
is shown in Figure 8), or a procedure named Main(), which you write yourself
and that executes when the application starts.
Figure 9. Setting Option Explicit and Option Strict to On will save you time when
debugging code later.
Option Explicit
Visual Basic .NET has its roots in VBA, or Visual Basic for Applications,
which in turn has its roots in the old BASIC programming language. In the old
BASIC language, there was no such thing as declaring a variable with the Dim
statementyou simply created variables on the fly and assigned values to
them. If you wanted to re-use a variable and happened to misspell the name,
the compiler simply took that as an indication that you were declaring a new
variable and barreled happily along. Obviously, this ease-of-use feature leads
to serious debugging issues when your code compiles, but doesn’t work
properly.
Option Explicit forces you to declare your variables, and this is a good thing.
The default setting in Visual Studio .NET is On, and we recommend that you
keep it set this way. It is like having a spell-checker for your variables. You’ll
learn more about what variables are and how to use them later in this chapter.
example, with Option Strict set to Off, the following code declares two
variables and automatically converts the Double value to the Integer value,
resulting in data loss. This is known as type coercion, where the compiler will
simply coerce the fractional Double data type to a whole-number Integer data
type, rounding the extra fractional information:
When you set Option Strict to On, the above code won’t even compileyou’d
need to reassure the compiler that data loss was okay by explicitly wrapping
the variable assignment in the CInt conversion function. You’d also need to
explicitly convert the Integer to a String for display in the MessageBox:
int = CInt(dbl)
MessageBox.Show(int.ToString)
This courseware uses the Option Strict = On setting in all of the examples, and
we recommend that you use it in all of your projects as well. Declaring
variables and working with Visual Basic .NET data types are covered in the
next section.
TIP: The modules that you create in Visual Basic .NET are really just classes
under the covers. Each of the procedures is defined as a shared method of the
hidden class, providing roughly the same behavior as Visual Basic 6.0
modules. Both modules and classes are saved with a vb file extension, as
shown in Figure 10.
Figure 10. Both modules and classes are saved with a .vb file extension.
See The following sample code declares a variable named srtTxt within the
btnVariables_Click btnVariables_Click event procedure. The As keyword indicates the data type,
String:
You can also take care of both the declaration of the variable and the
assignment of the value in one statement:
If the declaration and the assignment statement are too long to read on one line
without scrolling, you can use a space and an underscore to indicate that the
same statement continues on the next line:
Object Variables
Declaring and instantiating an object variable does not employ different syntax
as it did in Visual Basic 6. Even though object variables don’t actually contain
the objects they point to, the syntax is the same as it is for value-type variables.
You declare the variable as the type of object you want to work with, in this
case a Button control:
btn = btnVariables
The following statement assigns the value of the strText String variable to the
Text property of the Button control:
btn.Text = strTxt
NOTE If you are a Visual Basic 6.0 programmer, one thing you should
make note of is that the Set keyword is no longer used in Visual
Basic .NET. The syntax for object variables is now the same as
that for regular variables.
Variable Scope
Variables are always declared inside of a containerin the previous example,
both local variables are contained in a procedure, which is in turn contained in
a module. If you move the variables outside of the procedure, you can declare
them using the Public or Private keywords:
• Use the Public keyword when you want the variable to be accessible
from anywhere within the same project, from other projects that
reference the project, and from assemblies built from the project. You
can declare a public element in a source file or inside a module, class,
or structure, but not within a procedure.
• Use the Private keyword when you want the variable to be accessible
only from within the same module, class, or structure. You can declare
a private element in a source file or inside a module, class, or
structure, but not within a procedure.
These keywords for determining the scope of variables are referred to as
access modifiers.
NOTE You can also use the Dim keyword interchangeably for Private,
but you should resist the urge to do so. The Private keyword
makes your code easier to read and your intentions clearer. Dim
mainly exists in the language for backwards compatibility with
older versions of the Visual Basic language.
When you create a class module, you also have other options:
Variable Lifetime
As mentioned earlier, variables declared with the Dim keyword are destroyed
when the procedure terminates. However, you can use the Static keyword if
you want to preserve the value of a variable. Declaring a variable as Static
doesn’t mean it is accessible outside of the procedureit isn’tbut it does
mean that next time around the value will be preserved.
See frmVariables The following example declares a static variable and a regular variable,
increments each one, and displays the results in a label control. The
String.Format method will be discussed later in this chapter.
sint = sint + 1
int = int + 1
If you click the button on the form a few times, the static variable will retain its
value, but each time the regular variable will have the same value since it is
destroyed after the procedure has run, as shown in Figure 11.
Block Scope
So far you’ve seen variables with different scope depending on where they are
declared. However, you can narrow the scope of a variable even further by
declaring it inside of a code block. This would include branching and looping
constructions, which will be discussed in detail later in this chapter. The
following example declares a variable inside of a loop. Once the code inside
the loop finishes, the intBlock variable goes out of scope and is inaccessible.
Constants
Constants obey many of the same scoping rules as variables, so you can declare them
in local procedures or have more global scope with the Public and Private keywords.
Where they differ from variables is that constants refer to unchanging constant values.
They are hard-wired on your code, and you cannot change their value at runtime the
way you can with variables. You declare constants in your procedures using Const
keyword (instead of Dim):
Const CompanyName = "MCW Technologies"
You then use constants in your code the same way you would variables:
lbl.Text = CompanyName
Table 1 shows the data types for Visual Basic .NET and the Common
Language Runtime. Each of the listed data types maps to a corresponding
structure in the System namespace, which is shown in the second column.
• The Boolean data type stores only True/False values. Although Visual
Basic .NET represents Boolean values as False = 0 and True = -1, this
is not so in other .NET-aware languages. Make sure to always use the
True and False keywords when working with Booleans.
• An Integer in Visual Basic .NET maps to a Long Integer in Visual
Basic 6.0. A Short in Visual Basic .NET maps to an Integer in Visual
Basic 6.0.
• The Decimal data type has replaced the Visual Basic 6.0 Currency
data type and supports far greater precision and functionality.
• There is no more Variant data type. Although the Object data type
may look like a replacement, it is not the same.
• Unsigned data types are not supported.
• The Char represents a single Unicode character. It allows you to work
with data one character at a time.
See frmDataTypes The code listing in frmDataTypes declares a variable named int as an Integer
data type and a variable named lng as Long:
If you type a period after you declare the variable (type int.), you will see
the IntelliSense dialog box shown in Figure 12.
Label1.Text = int.ToString
Figure 13. Displaying GetType, ToString, MinValue, and MaxValue for Integer
and Long Integer Visual Basic .NET data types.
Conversion Functions
Explicitly converting from one data type to another often becomes necessary
when Option Strict is turned on. All of the conversion functions are listed in
Table 3, and follow the general syntax shown here for CBool where the
expression argument is the value to be converted:
CBool(expression)
Note the various ranges for the expression argument in Table 3. If the value
you are trying to convert exceeds the range, you’ll get an overflow error when
converting from one data type to another.
CType(expression, typename)
See The code in frmConversions shows a couple of the conversion functions and
frmConversions the results, as shown in Figure 14.
You can convert a Double to an Integer where the decimal values are
truncated. You can also convert an Integer to a Long Integer, because Longs
are wider than Integers.
However, you can’t convert a Double to a Short where the non-decimal value
would cause an overflow error, as happens here when the value of dbl is
123,456,789. The maximum value for Short is 32,767.
Operators
Table 4 lists operators commonly used in Visual Basic .NET expressions.
Although many of the operators used in Visual Basic .NET may be familiar to
users of Visual Basic 6.0, there are also some new operators that are more
directly related to C++. In addition to =, <>, > and <, you also have +=, *=, /=,
\=, &= and -=. These new operators allow you a convenient shorthand when
you want to operate on existing values. AndAlso and OrElse operators let you
short-circuit the And and Or operators, respectively. If the first condition is
true, the second part never gets called.
See frmOperators Figure 15 shows using a few of the operators that work with Integer variables.
One interesting thing to note is that the last expression uses integer division. If
you attempt to use regular division, you receive an error message. This is
another effect of the Option Strict settingVisual Basic .NET performs an
implicit conversion to the Double data type under the hood when performing
regular division. Even though you’ve declared both variables as Integer, you
still get the error.
End Function
That’s ityou’ve written a very simple function. Most of the functions will be
more complex than this and will consist of multiple statements, but the general
syntax is the same.
A sub procedure has slightly different syntax because it does not return a
result:
End Sub
In this case, the results are written to the Text property of a Label control since
there is no way for the sub procedure to return data by itself:
Executing Procedures
See To call the WhatDayIsIt function and assign the results to a Label control, use
frmProcedures.vb this syntax:
lblResults.Text = WhatDayIsIt()
To execute the WhatDaySub sub procedure, you can simply type the name of
the procedure (don’t forget the empty parentheses):
WhatDaySub()
Passing Arguments
Let’s say you wanted to pass a date to your procedure instead of it being hard-
wired to today’s date. You could pass that value to your function as long as
you declare it when you define your function. Both subs and functions work
with arguments.
NOTE The term argument is often used interchangeably with the term
parameter. The difference between the two is that a parameter is
the definition of what type of value you can pass to a procedure,
and an argument is the actual value that is passed in.
The following example shows the argument dtDate defined as a Date data
type, otherwise the function is the same as the one shown in the previous
example.
Return dtDate.DayOfWeek.ToString
End Function
lblResults.Text = WhatDayParam(dt))
Looping
See All programming languages provide syntax that allows you to iterate through
frmLoopsControl blocks of code until a condition has been met (or while a condition exists).
There are four basic loop types in Visual Basic .NET:
• For…Next
• For Each…Next
• Do…While
• Do…Until
For Loops
A basic For/Next loop uses a variable as a counter, as shown in the following
sample code. The bracketed text indicates optional syntax. For example, if you
leave out the Step 1 instruction, then the statements will repeat three times, or
once for each step, since the default is to only step once. You can change the
step value to another number, or step backwards by supplying a negative
number and stepping from 3 to 1.
The bracketed [int] after the Next statement is also optional, but recommended.
It’s conceivable that you may write nested For/Next loops using different
counter variables, and explicitly spell out which one you’re using. This makes
your code more readable.
The For/Each loop shown here lets you traverse the array of characters that
comprise the string “CAT”, one character at a time. The For/Each loop is
capable of walking through any type of collection.
Do Loops
A For/Next loop lets you loop when you know how many times you want to
loop. A Do loop lets you specify a condition, and depending on how you word
the loop, lets you repeat statements either until a condition is true, or while a
condition is true.
The following example always runs the inside statements at least once until the
condition (int = 3) is True:
Do
int = int + 1
Loop Until int = 3
If you want to check the condition first, and then execute the statements until
the condition is true, write the loop this way:
This loop always executes the inside statements at least once, and then
continues while the condition remains True:
Do
int = int + 1
Loop While int < 6
If you want to check the condition first, and then run the inside statements
while the condition remains true, then write the loop this way:
NOTE If you need to, you can supply conditional logic and an Exit Do
statement to exit a loop prematurely as part of a condition.
A new variation of the While loop in Visual Basic .NET is While/End While.
Control Flow
You’re probably already familiar with control flow statements from other
programming languages. Visual Basic .NET doesn’t have much in the way of
The If Statement
The If statement tests for a condition, and if the condition is True, any
statements following the Then statement are executed. If there is only one
statement, you can write it on one line:
However, chances are that you are going to need to add something to the If
statement later. So you’re better off doing a little more typing at the outset and
writing it on three lines, terminating with an End If statement:
If you want to execute some other statements if the condition is False, you can
add an Else statement:
You can add as many additional ElseIf conditions as you like. However, in
some cases your code may be more readable if you replace the multiple ElseIf
conditions with a Select Case statement.
Select Case
The Select Case statement allows you to branch depending on the output of an
expressionyou’re not limited to True/False like you are with the If
statement. The CalcQuartile example takes an argument of a single letter of the
alphabet, and determines which quartile it falls in. The breakdown is A-F (1),
G-L (2), ' M-S (3), and T-Z (4). This example is more complex than you
would need it to be in an attempt to show all the possible ways to use the Case
statement.
The sample code contains some built-in functions you may not be familiar
with and which will be explained in other chapters. If you want to test the Case
Else statement, pass a tilde (~) as the strValue argument.
Enumerations
Enum Rating
Low = 0
SoSo = 1
Medium = 2
Alright = 3
WayCool = 4
End Enum
Enumerations are declared outside the scope of a procedure, and if you don’t
supply a value, then the default is to use the Integer data type and start the
numbering at zero. However, you’re not restricted to declaring your
enumerations this wayyou can specify a different data type, as shown in
Figure 16.
In addition to coding your own enumerations, you will undoubtedly notice that
Visual Basic .NET uses them all over the place. For example, the Msgbox
function uses enumerations for specifying which button and icons will be
displayed. The syntax is very similar to that for Visual Basic 6.0:
The following example uses both the custom Rating enumeration and the
MsgBoxStyle enumerations. The code declares a Rating object, and sets it to
the desired enumeration, WayCool. In the MsgBox function, if you want to use
more than one enumeration (an icon plus a button, or anything else), you must
use the Or operator.
MsgBox( _
rateMe.ToString, _
MsgBoxStyle.Information Or MsgBoxStyle.OKOnly, _
"Enumerations")
WARNING! The plus sign (+) doesn’t work for combining MsgBoxStyle
enumerations when Option Strict is turned on.
Summary
• The vbc command line compiler lets you compile applications outside
of Visual Studio .NET.
• A console application can be executed from a command prompt.
• You need to configure options in your profile and in the project
properties that control how code behaves.
• You should always set Option Explicit and Option Strict to On.
• Option Strict disables type coercion.
• All form and module objects are classes in .NET.
• Avoid using reserved words when naming variables.
• The Set keyword is no longer used to instantiate object variables.
• Variables declared with the Dim keyword are destroyed when the
procedure terminates.
• Variables declared with the Static keyword retain their value.
• A block variable is destroyed when the block of code in which it was
declared terminates.
• Data types are the same for all .NET languages and different from
those in Visual Basic 6.0.
• The Boolean data type stores only True/False values.
• An Integer in Visual Basic .NET maps to a Long Integer in Visual
Basic 6.0 and a Short in Visual Basic .NET maps to an Integer.
• The Decimal data type has replaced the Visual Basic 6.0 Currency
data type and has an expanded range.
• The Variant data type found in Visual Basic 6.0 has been removed.
• Data types are objects, and have methods and properties.
• Conversion functions are available to convert one data type to another.
• Functions return a value, while sub procedures do not.
• Date values must be surrounded by pound signs (#), and string values
must be surrounded by double-quotes (").
• Looping syntax that allows you to iterate through blocks of code until
a condition has been met or while a condition exists.
• An If statement conditionally executes statements.
• The Select Case statement allows you to branch depending on the
output of an expression.
Questions
1. What tools do you need to create a console application?
3. What keyword do you use when you want a local variable to retain its
value the next time a procedure is called?
5. What delimiters are required for literal string values in Visual Basic .NET?
Literal date values?
Answers
1. What tools do you need to create a console application?
The vbc command-line compiler and a text editor
3. What keyword do you use when you want a local variable to retain its
value the next time a procedure is called?
Static
5. What delimiters are required for literal string values in Visual Basic .NET?
Literal date values?
Strings require double-quotes, dates require the pound sign.
Lab 4:
Visual Basic .NET
Nuts and Bolts
TIP: Because this lab includes code that you must type in, we’ve tried to make it
simpler for you. You’ll find all the code in NutsBoltsLab.txt, in the same
directory as the sample project. To avoid typing the code, you can copy/paste
it from the text file instead.
Lab 4 Overview
In this lab you’ll learn how to create a simple console application and how to
create a simple form application while working with variables, data types, and
procedures.
Objective
In this exercise, you’ll configure the command line compiler (vbc.exe) so that
it works on your computer. You will then use Notepad to create a simple
application that returns the current date and time. You will compile the
application and execute it from the command prompt.
Things to Consider
• What Visual Basic .NET function returns the current date and time?
• How do you compile a command line application?
• How do you execute your compiled application?
Step-by-Step Instructions
1. Open a Command Prompt window by choosing Programs|Microsoft
Visual Studio .NET|Visual Studio .NET Tools|Visual Studio .NET
Command Prompt from the Windows Start menu.
vbc
and press Enter. You will see all of the possible compiler options, as
shown in Figure 19.
Note that in order to use a DateTime variable and the Now() function, you
must fully-qualify them in order for the compiler to be able to compile
them.
c:\DateTimeReturn.vb
vbc c:\DateTimeReturn.vb
8. To clean up and remove the clutter from your root drive, open an Explorer
window and delete the following files:
c:\DateTimeReturn.vb
c:\DateTimeReturn.exe
Objective
In this exercise, you’ll create a constant for your company name that will be
available to any procedure in frmMain. You’ll write a procedure to calculate
the weekday of a day in the future. The number of days in the future is passed
as an argument to the function. The function returns the day name in a string.
You will display the day returned in a label control on frmMain. You’ll call the
function and test it to make sure that the value being passed to it is numeric. If
it isn’t, you’ll display a message box informing the user to enter a number.
You’ll set the focus to the text box so the user can enter a number.
Things to Consider
• What keyword do you use to declare a constant that is visible to all
procedures in a form?
• How do you declare a function that takes an input parameter of a
number and returns a string?
• How do you call the function and ensure that a numeric value is being
passed?
• How do you display a constant in a MsgBox?
Step-by-Step Instructions
1. Declare a constant outside of any procedure listings with your company
name, replacing “My Company” with any company name of your
choosing. The constant should be available to any procedure in frmMain:
4. Set dtFuture variable to use the DateAdd function to find the date the
specified number of days in the future:
Return dtFuture.DayOfWeek.ToString
If IsNumeric(txtNumDays.Text) Then
strReturn = CalculateDay(CInt(txtNumDays.Text))
lblResults.Text = strReturn
8. The Else part of the If statement displays a MsgBox for the user to enter a
valid number. Use the Exclamation and OKOnly enumerations for the
buttons. Use the Constant you defined in Step 1 in the Title for the
Msgbox. Clear the lblResults Label control and the txtNumDays TextBox
control by setting their Text property to String.Empty. Set the focus to the
txtNumDays control and close the If construct with an End If:
Else
MsgBox("Please enter a valid number", _
MsgBoxStyle.Exclamation Or MsgBoxStyle.OKOnly, _
Company)
lblResults.Text = String.Empty
txtNumDays.Text = String.Empty
txtNumDays.Focus()
End If
If IsNumeric(txtNumDays.Text) Then
strReturn = CalculateDay(CInt(txtNumDays.Text))
lblResults.Text = strReturn
Else
MsgBox("Please enter a valid number", _
MsgBoxStyle.Exclamation Or MsgBoxStyle.OKOnly, _
Company)
lblResults.Text = String.Empty
txtNumDays.Text = String.Empty
txtNumDays.Focus()
End If
End Sub
10. Test the procedure by typing a numeric value in the text box and clicking
the Go button. The results should look like those shown in Figure 21.
Figure 22. This is what you see when you don’t enter a numeric value.