Chapter 2. Programming with Visual Basic

The Visual Basic 2005 IDE is a powerful RAD tool, but as you saw in Chapter 1, sooner or later you have to roll up your sleeves and write some code, whether it’s to handle a simple button event or perform a complex series of calculations on stored data. In this chapter, you’ll take a look at the syntax of the VB 2005 language itself. While VB 2005 is a member in good standing of the .NET family of languages, it retains much of the flavor of its VB 6 lineage. This chapter will get you quickly up to speed with VB 2005 language and along the way will show you how some of its features have changed from those of VB 6.

Data Types

Table 2-1 lists the data types supported by VB 2005 and their counterparts in VB 6. If the size of a VB 6 type differs from that of its corresponding VB 2005 type, its size in bytes is shown in parentheses. For example, the Currency type (which takes up 8 bytes) in VB 6 is replaced in VB 2005 by the Decimal type. The old Decimal type (which takes up 12 bytes in VB 6), is now 16 bytes. Integer is now 4 bytes, instead of its 2 bytes in VB 6. Likewise, the Long data type is now 8 bytes, instead of its 4 bytes in VB 6.

Tip

VB 6 Tip: The venerable VB 6 Variant data type in VB 6 is no longer supported in VB 2005; you should use the Object type instead. Object and the types that derive from it are discussed at greater length in Chapter 3.

Table 2-1. Data types in VB 2005

VB 2005 type

Size (bytes)

VB 6 type (size in bytes)

Boolean

Depends on implementing platform

Boolean

Byte

1

Byte

Char

2

N/A

Date

8

Date

Decimal

16

Currency (8), Decimal (12)

Double

8

Double

Integer

4

Integer (2)

Long

8

Long (4)

Object

4

Variant

SByte

1

N/A

Short

2

N/A

Single

4

Single

String (variable size only)

Depends

String (supports fixed and variable size)

UInteger

4

N/A

ULong

8

N/A

UShort

2

N/A

User-Defined (Structure)

Depends

User-Defined (Type)

In both VB 6 and VB 2005, data types fall into one of two categories based on how they are stored and accessed:

Value types

A value type holds its data within its own memory allocation. You can access a value type directly without having to create a reference to it. Examples of value types are Integer and Single.

Reference types

A reference type contains a pointer to another memory location that holds the data. Examples of reference types are String and Object. We will discuss reference types in more detail in Chapter 3.

Variables in an application are stored in one of two different locations in memory: either on the stack or on the heap. Stacks are used for storing variables created in a function and are destroyed when the function exits. A heap, on the other hand, is used to store long-lived variables such as global and static variables.

Value types are stored directly on the stack at execution time, as opposed to being stored on the heap, as is done for reference types. You can access a value type directly without needing to create a reference to it. For a reference type, you must use a variable that contains a reference to the value of the type.

Variables

In VB 2005, you declare a variable with the Dim (dimension) keyword and you specify its type using the As keyword:

            Dim num1
     Dim num2 As Integer

The first statement declares num1, by default, to be an Object type. The Object type is the base class of all the classes in the .NET Framework. You can think of the Object type as equivalent to the Variant type in VB 6.

The second statement explicitly declares num2 to be an Integer variable.

The following statements declare num1 as a Short type and then assign a value to it:

	 '---range: -32768 <--> 32767
	 Dim num1 As Short
	 num1 = 32767

You should always specify the data type of a variable, because this assures the variable is strongly typed. Strong typing reduces the likelihood of runtime errors and makes your application much more efficient.

Tip

In VB 2005, to ensure that variables are declared with a data type (strongly typed), you should add the Option Strict On statement at the top of your code file. All variables must now be declared with a type.

You’ll learn more about the importance of strong typing, also known as early binding, in Chapter 3.

In VB 2005, you must declare all of the variables that you use, although you can work around this restriction and use variables without first declaring them with the Option Explicit Off statement. VB 2005 turns on Option Explicit On by default.

Tip

VB 6 Tip: VB 6 turns on Option Explicit Off by default. In both VB 6 and VB 2005, it is advisable for you to turn Option Explicit on, because using variables without first declaring them can easily inject potential bugs into your program.

As shown in Figure 2-1, when you assign the value of one value type to another (num2 = num1), VB 2005—or more correctly, .NET—makes a copy of the value type:

    Dim num1 as Short
	Dim num2 as Short
	num1 = -32768
	num2 = num1
Representation of a value type in memory
Figure 2-1. Representation of a value type in memory

Contrast this to the reference type. When you assign the value of a reference type to another, it causes the second variable to make a reference to the first without creating another copy of the value. The following example assigns one string variable to another:

	Dim str1, str2 As String
	str1 = "VB"
	str2 = str1

The memory allocation of str1 and str2 is as shown in the Figure 2-2.

Representation of a reference type in memory
Figure 2-2. Representation of a reference type in memory

Unlike VB 6, with VB 2005, you can declare two variables to be of the same type in a single statement, as follows:

	Dim num1, num2 As Short

Tip

VB 6 Tip: In VB 6, if you declare two variables in the same statement, as in the following Dim statement, the results are not the same:

	Dim num1, num2 As Short

Here, num1 is of the Variant type and num2 is of the Short type.

In VB 2005, you can also declare two variables of different data types in the same statement:

	Dim num1 As Short, num2, num3 As Integer

In this case, num1 is declared as Short, and num2 and num3 are both of type Integer.

Unlike VB 6, in VB 2005, you can declare and initialize a variable in the same statement:

	Dim num1 As Short = 56

VB 2005 now supports three new unsigned data types: UShort, UInteger, and ULong.

Tip

In VB.NET 2002 and 2003, you can use the .NET Frame-work’s unsigned types, but you cannot perform mathematical operations on them. With the new unsigned data type support in the new VB 2005, you can now do so.

The following statements declare unum as an unsigned 16-bit integer:

	Dim unum As UShort
	unum = 65535

Constants

While variables are a powerful tool, there are times when you want their values to remain constant. Perhaps your program makes repeated use of the value of pi or the natural logarithm e. A constant is like a variable in that it can store a value; unlike a variable, the value of a constant cannot be changed while the program runs. You declare constants using the Const keyword. The following definition assigns the value 3.14 to a constant whose name is pi and then uses it in calculating the area of a circle:

	           Const pi As Double = 3.14
	Dim radius as Double = 5
	Dim area as Double = pi * radius ^ 2

A constant of this type is sometimes called a symbolic constant, because it uses a word to represent a value. VB 2005 supports two additional kinds of constants: literals (see “Literals”) and enumerations, or enums (See “Enumerations”).

Literals

As in VB 6, a literal, or literal constant, as it is sometimes called, represents a particular value in text. For example, the number 32, as it appears in this sentence, is a literal constant. The value of 32 is always 32. Likewise, a quoted string like “Hello World” is also a literal constant. Literal types include Booleans, integers, floating-point numbers, strings, characters, and dates. Any number that is within the range of Integer types, such as 32, is an Integer type by default.

For example, the following statements assign the literal A to ch1 and ch2, both of which are Char types:

	'---assign the character "A" to ch1 and ch2
	Dim ch1 As Char = "A"c
	Dim ch2 As Char = Chr(65)
	Dim longValue as Long = 100L

To represent the quotation character (“) in a string variable, use the quotation character twice in succession, as in the following snippet:

	Dim str As String
	' assigns str to "He said: "VB is so cool!""
	str = "He said: ""VB is so cool!"""

To assign a date and time to a DateTime variable, use the # character:

	Dim timeNow As DateTime
	timeNow = #3/22/2005 10:01:19 AM#

To represent a large number, you can use the exponent symbol (E) to separate its mantissa (the significant digits; 3.8896, in the example below) and its exponent (a power of 10; 23, in this case):

	Dim f As Double
	f = 3.8896E+23

Enumerations

Sometimes it is easier to work with named constants than with numeric constants. Enumerations provide a powerful tool for creating logically related collections of named constants, such as the names of the primary colors, or the days of the week. For example, you might wish to represent the days of the week with numbers, such as 1 for Monday, 2 for Tuesday, and so on.

But when it comes to writing a program, it will likely be more intuitive to use the names of the days instead. You can do so by declaring an enumeration that associates each day of the week with a number.

Tip

VB 6 Tip: Enumerations are not new in VB 2005; VB 6 programmers should already be familiar with enumerations.

The following shows the Week enumeration:

	              Enum Week
		 Sunday = 0
		 Monday = 1
		 Tuesday = 2
		 Wednesday = 3
		 Thursday = 4
		 Friday = 5
		 Saturday = 6
    End Enum

To use the enumeration, declare a variable of type Week:

	Dim theWeek As Week

You can now assign the day of a week using a named constant:

	theWeek = Week.Monday ' or
	theWeek = 1           ' both are equivalent

Tip

Note that if you turn Option Strict On, the second statement above should be:

	theWeek = CType(1, Week)

You need to explicitly convert the Integer value to the enumeration. In “Type Conversion,” later in this chapter, you will learn about the Option Strict statement in more detail.

If you do not explicitly perform the conversion, Visual Studio 2005 will underline the number 1. You can position your cursor under the number and click on the down arrow (see Figure 2-3). Visual Studio 2005 will suggest to you the remedy. This feature is known as AutoCorrect.

To print out the month, you can use either of the following:

	MsgBox(theWeek)          ' prints out 1
	MsgBox(theWeek.ToString) ' prints out Monday

Besides defining your own enumerations, there are also predefined enumerations with which you might already be familiar. For example, the result from the MsgBox function is an enumeration called MsgBoxResult:

AutoCorrect in Visual Studio 2005
Figure 2-3. AutoCorrect in Visual Studio 2005
	Dim response As MsgBoxResult
	response = MsgBox("Are you sure?", MsgBoxStyle.YesNo)
	If response = MsgBoxResult.Yes Then
       ' do something
    Else
       ' do something
    End If

Strings

As in VB 6, VB 2005 String types are used to represent text and are a good example of a reference type, as you saw in “Variables,” earlier in this chapter. Strings in .NET are immutable, which means that once you’ve assigned a value to a string variable, it cannot be changed. If the value of a string variable is changed, another string object is created during runtime. Consider this example:

	Dim st As String
	st = "Hello"
	st &= " World!"
	MsgBox(st) ' prints "Hello World!"

In the above example, two string objects are involved: one for the initialization and one for the concatenation. This problem gets worse if you are doing concatenation in a loop, like the following:

	Dim i As Integer, str As String = ""
	For i = 0 To 10000
       str &= i.ToString
    Next

A much more efficient way to manipulate strings is to use the StringBuilder class, located in the System.Text namespace:

	Dim i As Integer, str As New _
       System.Text.StringBuilder()
    For i = 0 To 10000
       str.Append(i.ToString)
    Next

Tip

The "_” (underscore) character is the continuation character in Visual Basic (all versions). It is used to break a long statement into multiple lines.

Arrays

As in VB 6, a VB 2005 array is a collection of variables in which each variable is identified by an index, like mailboxes on a street or players on a team.

For example, the following declaration defines num1 as an array by adding open and closed parentheses to its name:

	Dim num1() As Integer

Note that this declaration simply declares num1 to be an array; the actual size of the array is not known yet. To get num1 to point to an actual array, use the New keyword:

	num1 = New Integer() {1, 2, 3}

num1 is now an array containing three members of Integer data type with values 1, 2, and 3.

Here are some other possible ways to declare and initialize an array:

	Dim num2(2) As Integer
	num2(0) = 1
	num2(1) = 2
	num2(2) = 3

The size of the array is one plus the number declared, as is the case in VB 6. In the above case, the valid index is from 0 to 2, giving a total of 3 members. Note that the following is not allowed:

	Dim num2(2) As Integer = New Integer
	'---Not allowed since size is
	'   already indicated

You can also combine the declaration together with the initialization:

	Dim num3() As Integer = _
        New Integer() {1, 2, 3}

The following are not allowed:

	Dim num3() As Integer = New Integer()
	'---Not allowed; missing {}

	Dim num3() As Integer = New Integer(3)
	'---Not allowed; missing {}

	Dim num3() As New Integer
	'---Not allowed, arrays cannot use New

	Dim num3() as New Integer() {1,2,3}
	'---Syntax error

Once an array is declared, you can change its size by using the ReDim keyword:

	Dim num4() As Integer() = New Integer() {1, 2, 3}
	ReDim num4(5)

Tip

VB 6 Tip: In VB 6, you can only ReDim an array if the array is initially declared as a variable length array, as the following shows:

	' array is fixed length
	Dim num1(3) As Integer
	ReDim num1(5) '---error

	' array is variable length
	Dim num2() As Integer
	ReDim num2(5) '---OK

When an array is redimensioned, all its previous values will be lost. To retain the previous values, use the Preserve keyword:

	ReDim Preserve num4(5)

VB 2005 adds the new To keyword. You can explicitly specify the range of an array using the To keyword:

	Dim num1(0 To 19) As Integer

Tip

Note that the To keyword is used only to make your code more readable; you cannot alter the lower bounds of the array to, say, 1. The only bound must be 0.

Note that in VB 6, you can change the base of an array using the Option Base statement. However, VB 2005 does not allow you to change the base of an array.

Type Conversion

You perform a type conversion when you need to convert or assign values from one type to another. This is also known in some circles as casting. Consider the following code:

	Dim num1 as Short = 25
	Dim num2 as Long
	num2 = num1

In this case, the VB 2005 compiler will automatically perform an implicit conversion from the Short type to the Long type. Since all the values that could be stored by the Short type can fit into a Long type, this conversion is known as a widening conversion and is a safe operation. The reverse of widening is a narrowing conversion, which is a conversion from a data type that has a larger range to one with a lower range. Consider the following:

	Dim num1 As Long = 25
	Dim num2 As Short
	num2 = num1

In this example, num1 may potentially contain a value that will cause an overflow in num2 if the assignment takes place. In VB 2005, you can restrict automatic data type conversion by using the Option Strict statement. By default, in VB 2005, the Option Strict statement is set to Off.

Tip

VB 6 Tip: In VB 6, there is no Option Strict statement. Hence, the design decision of VB 2005 was to turn Option Strict Off by default so that VB 6 code can be migrated easily.

If you turn Option Strict On, you will need to perform an explicit conversion (or else the compiler will complain):

    '---if option strict on
	num2 = CShort(num1)
	'--OR--
	num2 = CType(num1, Short)

Tip

You should preferably turn Option Strict On, so that any narrowing operations you are doing are flagged. This will allow you to take action to catch potential errors that might result from a narrowing conversion. Note that in VB 6, performing a narrowing conversion will not set off a warning since the Option Strict statement is not supported.

VB 6 Tip: The familiar type conversion functions like CInt, CStr, and CSng in VB 6 are still supported in VB 2005. In addition, VB 2005 supports the general purpose CType function, which allows you to specify the data type to convert to.

When performing a narrowing conversion, you should always take care to ensure that the operation will not result in a runtime error, such as performing the operation within a Try-Catch block. See “Error-Handling,” later in this chapter, for more details.

Operators

VB 2005 supports the various operators shown in Table 2-2.

Table 2-2. Operators supported in VB 2005

Type

Language element

Description

Arithmetic

^

Raises to the power of

 

Subtraction

 

*

Multiplication

 

/

Division

 

Integer Division

 

Mod

Modulus (remainder)

 

+

Addition

Assignment

=

Assigns a value to a variable or property

 

^=

Raises the value of a variable to the power of an expression and assigns the result back to the variable (new in VB 2005)

 

*=

Multiplies the value of a variable by the value of an expression and assigns the result to the variable (new in VB 2005)

 

/=

Divides the value of a variable by the value of an expression and assigns the result to the variable (new in VB 2005)

 

=

Divides the value of a variable by the value of an expression and assigns the integer result to the variable (new in VB 2005)

 

+=

Adds the value of an expression to the value of a variable and assigns the result to the variable (works for strings as well) (new in VB 2005)

 

-=

Subtracts the value of an expression from the value of a variable and assigns the result to the variable (new in VB 2005)

 

&=

Concatenates a String expression to a String variable and assigns the result to the variable (new in VB 2005)

Comparison

=

Equal

 

<>

Not equal to

 

<

Less than

 

>

Greater than

 

<=

Less than or equal to

 

>=

Greater than or equal to

 

Like

Compares a string against a pattern

 

Is

Compares two object reference variables

 

IsNot

Compares two object reference variables

Concatenation

&

Concatenates two strings

 

+

Concatenates two strings

Logical/bitwise operations

Not

Logical negation on a Boolean expression

 

And

Logical conjunction on two Boolean expressions, or bitwise conjunction on two numeric expressions

 

Or

Logical disjunction on two Boolean expressions, or bitwise disjunction on two numeric values

 

Xor

Logical exclusion operation on two Boolean expressions, or bitwise exclusion on two numeric expressions

 

AndAlso

Short-circuiting logical conjunction on two expressions (new in VB 2005)

 

OrElse

Short-circuiting logical disjunction on two expressions (new in VB 2005)

Miscellaneous operations

AddressOf

Creates a procedure delegate instance that references the specific procedure (new in VB 2005)

 

GetType

Returns a Type object for the specified type (new in VB 2005)

When testing for the equality of numeric values, use the = operator. Use the Is operator to test the equality of objects. Chapter 3 will discuss the use of the Is operator in greater detail.

Tip

VB 6 Tip: Of particular interest to VB 6 users is the new support for assignment operators in Visual Basic 2005. In VB 6, to increment a variable, you must write code that looks something like this:

	var = var + 1

In Visual Basic 2005, you can now rewrite the line as:

	var += 1

The IsNot operator is new in VB 2005. Often you need to negate the comparison of an object, such as:

	Dim obj As Button
	If Not obj Is Nothing Then
	   ' obj contains an object reference
       .…
    End If

In this case, your code will be more readable if you use the IsNot operator:

	If obj IsNot Nothing Then
       ' obj contains an object reference
       .…
    End If

Statements

As in VB 6, a complete program instruction in VB 2005 is called a statement. Programs consist of sequences of statements. You end each statement with a carriage return.

In VB 2005, spaces, tabs, and carriage returns (newlines) are considered to be "whitespace.” Extra whitespace is ignored in VB 2005, as in VB 6, a feature that many consider an endearing (and forgiving) quality of the language.

Decision-Making (Branching) Statements

VB 2005 retains the traditional VB 6 statements for decision making but adds a few new wrinkles of its own. Decision-making statements fall into two categories:

  • If-Then-Else

  • Select-Case

If-Then-Else

Just as in VB 6, in VB 2005, you make decisions using the If-Then-Else construct.

	                 If <condition> Then
       <statement(s)>
    Else
       <statement(s)>
    End if 

Here is a short example:

	Dim day As Short = 4
	Dim dayofWeek As String
	If day = 1 Then
       dayofWeek = "Monday"
    End If

In the preceding code, if day is equal to 1, the string “Monday” is then assigned to the dayofWeek variable. For a one-line statement, you can shorten the above code to:

	If day = 1 Then dayofWeek = "Monday"

However, if you have multiple statements to execute if a condition is met, use of the End If statement is mandatory. VB 2005 lets you pack a block of conditional code into a single line. For example, the following block of code:

	If day = 1 Then
        dayofWeek = "Monday"
        currentTime = Now
    End If

is equivalent to this single line of code:

	If day = 1 Then dayofWeek = "Monday" : currentTime = Now

The grouping of several statements into a single line using the : character, as shown in the preceding snippet, is useful in cases where you want to group multiple statements into a single line to improve the readability of your code. The grouping feature is also useful for organizing a related group of variables.

You can also nest several If-Then-Else statements, as shown in Example 2-1.

Example 2-1. Nesting If-Then-Else statements
Dim day As Short = 4
Dim dayofWeek As String

If day = 1 Then
   dayofWeek = "Monday"
Else 
   If day = 2 Then
      dayofWeek = "Tuesday"
   Else
      If day = 3 Then
         dayofWeek = "Wednesday"
      Else
         If day = 4 Then
            dayofWeek = "Thursday"
         Else
            If day = 5 Then
               dayofWeek = "Friday"
            Else
               If day = 6 Then
                  dayofWeek = "Saturday"
               Else
                  If day = 0 Then
                     dayofWeek = "Sunday"
                  Else
                     Msgbox("Number out of range")
                  End If
               End If
            End If
         End If

     End If
   End If
End If

Note the matching End If statement for each If statement. If you have multiple nested If-Then-Else constructs, you can simplify the above code using the ElseIf keyword (also supported in VB 6), as shown in Example 2-2.

Example 2-2. Using the ElseIf keyword
If day = 1 Then
    dayofWeek = "Monday"
ElseIf day = 2 Then
    dayofWeek = "Tuesday"
ElseIf day = 3 Then
    dayofWeek = "Wednesday"
ElseIf day = 4 Then
    dayofWeek = "Thursday"
ElseIf day = 5 Then
    dayofWeek = "Friday"
ElseIf day = 6 Then
    dayofWeek = "Saturday"
ElseIf day = 0 Then
    dayofWeek = "Sunday"
Else
    MsgBox("Number out of range")
End If

Note that if you use the ElseIf keyword, the number of End If statements is reduced to one (in this example).

Select…Case

If you have multiple conditions to test, it is often much easier (and more readable) to use the Select…Case construct. Example 2-3 shows a rewrite of the previous code segment using the Select…Case construct.

Example 2-3. Using the Select…Case statement
                     Select Case day
   Case 1 : dayofWeek = "Monday"
   Case 2 : dayofWeek = "Tuesday"
   Case 3 : dayofWeek = "Wednesday"
   Case 4 : dayofWeek = "Thursday"
   Case 5 : dayofWeek = "Friday"
   Case 6 : dayofWeek = "Saturday"
   Case 0 : dayofWeek = "Sunday"
   Case Else : Msgbox( _
       "Number out of range")
End Select

Looping (Iteration) Statements

VB 2005 provides several looping constructs. They are all supported in VB 6 as well, unless otherwise noted:

	For
	For-Each
	While
	Do-While
	Do-Until

Each of the following examples (Example 2-4 through Example 2-8) prints a series of array members with indexes ranging from 0 to 5 using one of the looping constructs supported by VB 2005.

Example 2-4. Using the For loop
Dim num() As Integer = {1, 2, 3, 4, 5, 6}
For n as Integer = 0 To 5
    Console.Write(num(n))
Next

Tip

VB 6 Tip: In VB 6, you need to declare the loop variant (n) in a separate statement. Only VB 2005 allows you to declare it and use it at the same time.

Example 2-5. Using the For-Each loop
Dim num() As Integer = {1, 2, 3, 4, 5, 6}
For Each i As Integer In num
    Console.Write(i)
Next
Example 2-6. Using the While loop
Dim num() As Integer = {1, 2, 3, 4, 5, 6}
Dim j As Integer = 0
While j <= 5
    Console.Write(num(j))
    j += 1
End While

Tip

VB 6 Tip: In VB 6, you use the While-Wend statement to implement a While loop.

Example 2-7. Using the Do-While loop
Dim num() As Integer = {1, 2, 3, 4, 5, 6}
Dim k As Integer = 0
Do While k <= 5
    Console.Write(num(k))
	k += 1
Loop
Example 2-8. Using the Do-Until loop
Dim num() As Integer = {1, 2, 3, 4, 5, 6} 
Dim m As Integer = 0
Do
    Console.Write(num(m))
    m += 1
Loop Until m > 5

Functions and Subroutines

VB 2005 supports both functions and subroutines. Basically, support for functions and subroutines is the same in VB 2005 as it is in VB 6. However, VB 2005 provides you with an additional way to return values in a function by means of the new Return statement. VB 2005 programmers have three choices: they can write their own functions, continue using most of the VB 6 functions they have come to know and love, or tap into the rich functionality of the .NET Framework Class Library through the new My namespace (see “My Namespace,” later in this chapter).

Function

A function is a block of code that performs some operations and then returns a value. For example, the following function Area takes in two input parameters, computes the area, and then returns the result:

     Public Function Area(ByVal length As Single, _
                 ByVal breadth As Single) As Single
         Dim result As Single
         result = length * breadth
         Return result
     End Function

To invoke a function, you simply call the function name with the required argument(s):

	 Dim areaOfRect As Single = Area(4, 5)

Tip

VB 6 Tip: In VB 6, only functions require the mandatory use of parentheses around the parameter list. But in VB 2005, all functions or subroutine calls require parentheses around the parameter list (even if the parameter list is empty).

The value returned by the Area function is then assigned to the areaOfRect variable.

In VB 6, you use the function name to return the value of a function, like this:

	Public Function Area(ByVal length As Single, _
	            ByVal breadth As Single) As Single
        Dim result As Single
        result = length * breadth
        Area = result
    End Function

In VB 2005, you can either use the Return keyword or the function name to return the value of a function. Note that when a Return statement is encountered in a function, the execution is immediately transferred back to the statement that called it.

Subroutine

A subroutine is similar to a function, except that it does not return a value. For example, the following subroutine PrintMessage accepts a single input parameter and prints a message box.

	Public Sub PrintMessage(ByVal str As String)
        MsgBox(str)
	End Sub

To invoke a subroutine, you simply call the subroutine name and pass it the required argument(s):

	PrintMessage("File deletion completed.")

Tip

VB 6 Tip: In VB 6, you can call the PrintMessage subroutine without using parentheses to enclose the parameter list:

	PrintMessage "File deletion completed."

Passing Arguments

There are two ways to pass values to a subroutine or function:

  • By value

  • By reference

Let’s take a closer look at these two methods in the following sections.

Passing by value

Consider the following subroutine:

	Public Sub ProcessValue(ByVal num As Integer)
        num += 1
        MsgBox("In ProcessValue(), num is " & num)
    End Sub

The ProcessValue subroutine takes a single input parameter: num. The parameter declaration is preceded by the ByVal keyword.

By default, Visual Basic 2005 passes an argument via ByVal. In VB 6, the default is ByRef (see "Passing by reference,” next).

The following statements call the ProcessValue subroutine and display a value at each stage:

	Dim num As Integer = 5
	MsgBox("Before ProcessValue(), num is " & num)
	ProcessValue(num) ' pass by value
	MsgBox("After ProcessValue(), num is " & num)

You will realize that the value of num remains at 5 before and after calling the ProcessValue subroutine.

As you can deduce, even though the variable num is modified within the subroutine, the change is not reflected outside the subroutine. When you pass an argument by value, a copy of the variable is created to be used within the subroutine. When the subroutine exits, the variable is destroyed.

Passing by reference

Consider the following subroutine:

	Public Sub ProcessValue(ByRef num As Integer)
        num += 1
        MsgBox("In ProcessValue(), num is " & num)
    End Sub

The ProcessValue subroutine takes in a single input parameter: num. The parameter declaration is preceded with the ByRef keyword.

The following statements call the ProcessValue subroutine and display the value at every stage:

	Dim num As Integer = 5
	MsgBox("Before ProcessValue(), num is " & num)
	ProcessValue(num) ' pass by value
	MsgBox("After ProcessValue(), num is " & num)

In contrast to passing by value, when you pass an argument by reference, the subroutine receives a reference that points to the location where the argument is stored in memory. When the variable is modified within the subroutine, the change will affect the original variable. Hence, the change remains even after the subroutine exits.

Optional parameters

Consider the following definition of a modified PrintMessage subroutine:

	Public Sub PrintMessage(ByVal str1 As String, _
				ByVal str2 As String, _
          Optional ByVal str3 As String = "rocks!")
       MsgBox(str1 & str2 & str3)
	End Sub

This version of the PrintMessage subroutine takes three input parameters: str1, str2, and str3. The first two are required; str3 is an optional parameter, as called out by the Optional keyword. For an optional parameter, a default value is required.

Optional arguments must always be declared last in a subroutine definition. You can specify one or more optional parameters.

Tip

VB 6 Tip: In VB 6, optional parameters are not required to have default values, but in VB 2005, optional parameters must have default values.

When you call the subroutine, you pass the arguments in the order specified by the parameter list. The following subroutine calls PrintMessage, passes the strings “Visual” and “Basic” as arguments, using the optional arguments in one case but not in the others:

	'--- with and without optional arguments

	' prints out Visual Basic rocks!
	PrintMessage("Visual ", "Basic ")

    ' prints out Visual Basic rocks!
	PrintMessage("Visual ", "Basic ", )

	' prints out Visual Basic really rocks!
	PrintMessage("Visual ", "Basic ", "really rocks!")

You can also leave out the optional argument by using a comma (,).

Error Handling

There are two main types of coding errors that programmers generally have to deal with:

  • Compile-time errors

  • Runtime errors

Tip

In VB 2005, the background compiler kicks into action every time you type in a line of code. It dynamically compiles your code and warns you of errors before you actually compile it.

In the former case, the compiler detects a syntax error and the IDE handles the error and calls it to the attention of the programmer so that immediate action can be taken to fix the problem. Runtime errors occur while an application is running. It is this type of error that must (and can) be prevented.

To ensure that an application is as robust and bug free as possible, it is important to anticipate as best you can all of the errors that might occur while your program is running. In VB 2005, error handling has been much improved over VB 6. VB 2005 now supports both structured and unstructured error handling.

Tip

VB 6 Tip: In VB 6, error handling was unstructured, performed using the primitive On Error and On Error Resume Next statements. The specific information about an error that occurred can be retrieved from the Err object.

Try-Catch-Finally

In VB 2005, you can implement structured error handling using the Try… Catch…Finally construct. Basically, you place any code that could possibly trigger a runtime error, such as a disk access, into a Try block. Any errors that happen within the Try block will be caught and serviced by the Catch block(s) that follow. This is where you can take actions to correct the error or clean up any resources that you’ve allocated. The Finally block is executed whether an error occur in the Try block or not. The Finally block is a good place to perform housekeeping chores such as closing a database or file connection.

Example 2-9 shows how you can use Try…Catch…Finally statements to catch errors at multiple levels within a procedure that performs an integer division of two numbers. Note the use of multiple Catch blocks to handle exceptions that range from the specific ( InvalidCastException and DivideByZeroException) to the most general (Exception).

Example 2-9. Using Try…Catch…Finally statements to handle runtime errors
'===Error Handling===
Dim num1, num2, result As Integer
Try
	num1 = InputBox("Please enter num1")
	num2 = InputBox("Please enter num2")

	result = num1  num2
	MsgBox(result)
Catch invalidCast As InvalidCastException
    MsgBox("Please enter numbers only")
Catch divisionByZero As DivideByZeroException
	MsgBox("Division by zero error")
Catch ex As Exception
	MsgBox(ex.ToString)
Finally
	MsgBox("This line is always printed.")
End Try

When the user enters a non-numeric input for one of the numbers, the InvalidCastException exception will be raised and the message “Please enter numbers only” will be printed. If the user enters a 0 for num2, it results in a division by zero error and raises the DivideByZeroException exception. The Exception exception is the root of all exceptions and will catch any exceptions not caught by the earlier Catch statements. The statement within the Finally block is always executed, regardless of whether any exception has been raised.

Throwing Exceptions

Besides catching errors using the Try…Catch…Finally construct and the predefined exceptions available in the .NET Class Library, you can also throw your own custom exceptions by using the Throw keyword. The Throw keyword allows you to throw an exception so that you can handle the exception with the structured exception-handling code.

Consider the following example:

	Public Function divide(ByVal num1 As Single, _
                           ByVal num2 As Single) _
				   As Single
        If num2 = 0 Then Throw New _
           Exception("num2 cannot be zero!")
        Return num1 / num2
    End Function

In this divide function, if num2 is zero, you will throw your own exception (using the Exception class) with your own custom error message.

A user of this function can then catch the error like this:

	Try
        MsgBox(divide(4, 0))
    Catch ex As Exception
		MsgBox(ex.ToString)
    End Try

The variable ex will contain detailed information of the exception when it occurs. To display the error message, simply use the ToString method.

My Namespace

One of the problems faced by VB 6 programmers moving to VB 2005 is figuring out which class in the .NET Framework is the appropriate class to use to solve a particular problem. To simplify the transition, VB 2005 provides the new My namespace, which encapsulates some of the most common functionalities that developers need in their daily work.

Tip

VB 6 Tip: Most VB 6 predefined functions are still supported in VB 2005. They are located within the Microsoft. VisualBasic namespace (which is automatically referenced by default in all VB 2005 projects) and so you can continue to use your favorite VB 6 functions without doing anything extra.

The My namespace exposes several areas of functionality, as shown in the IntelliSense pop-up in Figure 2-4.

The objects exposed by the My namespace
Figure 2-4. The objects exposed by the My namespace

The aim of the My namespace is to provide direct access to commonly used libraries (in the .NET Framework) like Resources that were previously difficult to access. The intuitive hierarchy of the My namespace provides a mechanism that VB 2005 developers can use to easily navigate the .NET Framework class libraries and locate the classes required to perform a particular task. For example, suppose you want to play an audio file in your application. Which class should you use? Using the My namespace, it is easy to locate the right class to use. As it turns out, the class to use can be found in My.Computer.Audio.Play!

The objects exposed by the My namespace are:

My.Application

Provides properties, methods, and events related to the current application.

My.Computer

Provides properties for manipulating computer components, such as audio, the clock, the keyboard, the filesystem, and so on.

My.User

Provides access to the current user’s security context. For Windows applications, the access is read-write, while access for web applications is read-only.

My.Forms

Provides properties for accessing an instance of each Windows Form declared in the current project.

My.Settings

Provides properties and methods for accessing the application’s settings.

My.Webservices

Provides properties for creating and accessing a single instance of each XML web service referenced by the current project.

Tip

The My namespace is not just a static shortcut to the class libraries in the .NET Framework. Depending on your project type, the My.Forms, My.Resources, My.Settings, and My. Webservices objects will dynamically display the relevant objects and classes.

Here are some examples of how to use the My namespace. You can use the My.Application object to discover the installation path of the current application:

	Dim appPath As String = _
	   My.Application.Info.DirectoryPath

You can use the My.Computer object determine whether a file exists. At the same time, you can also play a system audio sound:

	Dim exists As Boolean
	exists = _
	   My.Computer.FileSystem.FileExists( _
	   "c:file.txt")
	If Not exists Then
       My.Computer.Audio.PlaySystemSound( _
          System.Media.SystemSounds.Exclamation)
       MsgBox("File does not exist")
    End If

You can also play a specific audio file:

	My.Computer.Audio.Play( _
       "C:WINDOWSMediachimes.wav")

File management is one of the most common tasks that developers need to perform. Using the My.Computer.FileSystem object, you can access all the various file handling routines in one place (see Figure 2-5).

The routines in the My.Computer.FileSystem object
Figure 2-5. The routines in the My.Computer.FileSystem object

Another useful object that resides in My.Computer is the Network object. With it, you can perform a task such as downloading a file from the network and saving it locally. The following example downloads a .gif file from a web site and saves to your local C: drive.

     My.Computer.Network.DownloadFile( _
         "http://www.oreilly.com/catalog/" & _
		 "covers/aspnetadn.s.gif", _
		 "c:images596008120.jpg")

In a Windows application, you can access the collections of forms in your application and their properties with the My.Forms object. For example, the following statements set the Opacity property of a form to 50%:

	My.Forms.Form1.Opacity = 0.5
	' ---equivalent to---
	Form1.Opacity = 0.5

If you have multiple web services references in a project, you can find them all in the My.WebServices object. For example, suppose you have added a web reference to the Translate web service in your application (see Figure 2-6) at http://www.webservicex.net/TranslateService.asmx?WSDL. The following example shows how to invoke the TranslateService web service through the My.WebServices object:

	MsgBox(My.WebServices.TranslateService.Translate( _
        net.webservicex.www.Language.EnglishTOFrench, "Hello"))

In a web application, you can use My.User to determine whether a user is authenticated:

	Response.Write(My.User.IsAuthenticated)
Adding a web reference
Figure 2-6. Adding a web reference

Summary

In this chapter, you have been taken on a whirlwind tour of VB 2005 syntax and seen how it compares with that of VB 6. If you are a VB 6 programmer, you’ll be happy to have discovered that much of what you already know is still supported (or enhanced) in VB 2005. The new My namespace is another productive feature that Microsoft has built into the language.

In the next chapter, you will learn how you can use the object-oriented programming support found in VB 2005 to become even more productive than you already are, and you’ll learn why object orientation is one of the most important additions to the Visual Basic language.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.201.32