Introduction to the VB .NET Language

Although this book is focused on the creation of applications, it's important that you have some fundamental knowledge of the VB .NET language. This chapter introduces you to some of the basic principles. For those of you with programming experience, you can probably skim over this chapter and move on. For those without any programming experience, this chapter will help you with some of the basic concepts used in most VB applications.

Variables

Variables are used in almost every VB application. They are simply used to store data in a memory location that you can access and manipulate as needed. For example, suppose you are developing an application that adds two numbers together. When writing the code, you could temporarily store the values of the two numbers in separate variables with a third variable holding the resultant value. Instead of referring to an actual memory location, VB allows us to use a variable name that we can declare to refer to these values. Declaring a variable is as simple as creating a name along with a specific data type. When you declare a variable, Visual Basic allocates a certain amount of memory for the variable to store the data. It is the data type that determines exactly how much memory is being put aside.

  Note 

If you don't specifically declare a data type, VB .NET assigns it to the Object data type. This is not a suggestion to do so; as for readability, you should always declare the data type, even if it is of type Object.

Table 5.1 details some of the variable types, the range of values they can store, and the memory that is allocated.

Table 5.1: Data types, size, and range of memory

Type

Size

Range

Boolean

4 bytes

True or False

Byte

1 byte

0-255 unsigned

Char

2 bytes

0-65,535 unsigned

Date

8 bytes

1/1/1 CE to 12/31/9999

Decimal

12 bytes

+/- 79,228,162,514,264,337,593,543,950,335

with no decimal point;

+/- 7.9228162514264337593543950335 with

28 places to the right of the decimal; smallest

nonzero number is

+/- 0.0000000000000000000000000001

Double

8 bytes

-1.79769313486231E308 to

-4.94065645841247E-324 for negative values;

4.94065645841247E-324 to 1.79769313486232E308

for positive values

Integer

4 bytes

-2,147,483,648 to 2,147,483,647

Long

8 bytes

-9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

Object

4 bytes

Any object type

Short

2 bytes

-32,768 to 32,767

Single

4 bytes

-3.402823E38 to -1.401298E-45 for negative

values; 1.401298E-45 to 3.402823E38 for positive values

String

10 bytes

+ 0 to approximately 2 billion Unicode characters (characters in string * 2)

With some of this basic information out of the way, we'll look at how variables are actually declared using the Dim keyword.

As in previous versions of Visual Basic, you use the Dim keyword. The following are some common examples of declaring variables:

Dim x as Single
Dim txt as String
Dim str as string
Dim oObj as Object

By default, when you declare a variable in VB, it is initialized to a standard value (numeric variables are set to 0, strings are initialized to an empty string ' ', and object variables are initialized to nothing). In VB .NET, you can now initialize variables to something other than their defaults when you declare them. Here are a few examples of initializing variables when declaring them:

Dim x as Single = 1.5
Dim txt as String = "Bob"
Dim Answer as Boolean = "True"

Variable declarations are usually very simple, although they can get a little more complicated when you invoke an object's constructors. Different constructors use different arguments to initialize the object. For example, suppose you need to initialize a string with 50 asterisks ('*'). You could manually type in 50 of them and it would work just fine, although you could also use a String variable constructor as follows:

Dim txt3 As New String("*", 50)

You can see that this is much easier than attempting to type out 50 asterisks and is also much more readable.

When multiple variables are declared on the same line, then its type is the same as the rest of the variables on the line. For example:

Dim x,y,z as Integer

This gives x, y, and z the Integer data type. You can take this a step further as well:

Dim x,y,z as Integer, a,b as String

This sets the x, y, z types to Integer and a, b types to String. In earlier versions of VB, these types of declarations could have caused some problems, so this is a welcome addition.

CTS

Before moving on, we look at a more exhaustive list of the data types supported in the .NET CTS, as shown in Table 5.2. It's worth noting that the CTS data types are either structures (which are value types) or classes (which are reference types).

Table 5.2: Data types supported in the .NET CTS

Data Type

CTS Type

Type

Storage

Value Range

Boolean

System.Boolean

Value (Structure)

2 bytes

True or False

Byte

System.Byte

Value (Structure)

1 byte

0 to 255 (unsigned)

Char

System.Char

Value (Structure)

2 bytes

A character code from 0 to 65,535 (unsigned)

Date

System.DateTime

Value (Structure)

8 bytes

January 1, 1 CE to December 31, 9999

Decimal

System.Decimal

Value (Structure)

12 bytes

+/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/- 7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest nonzero number is +/-0.000000000000000000000000000153

Double (double-precision floating point)

System.Double

Value (Structure)

8 bytes

-1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values

Integer

System.Int32

Value (Structure)

4 bytes

-2,147,483,648 to 2,147,483,647

Long (long integer)

System.Int64

Value (Structure)

8 bytes

-9,223,372,036,854,775,808 to 9,223,372, 036,854,775,807

Object

System.Object

Reference (Class)

4 bytes

Any type can be stored in an Object variable

Short

System.Int16

Value (Structure)

2 bytes

-32,768 to 32,767

Single (single- precision floating point)

System.Single

Value (Structure)

4 bytes

-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values

String

System.String

Reference (Class)

10 bytes +

0 to approximately 2 billion

(variable-length)

   

(2 * string length)

Unicode characters

User-Defined

(inherits from

Value (Structure)

Sum of the

Each structure member has a range

Type (structure)

System.Value Type)

 

sizes of its members

determined by its data type and is independent of the ranges of the other members

Scope

The scope of a variable determines where in a program it is visible to the code. Variables and constants (we look at constants in the next section) both have a scope, which allows a programmer to decide when a variable can be referred to in the rest of the program.

Block Level and Procedure Level Scope

If a variable is declared inside a block of code, then the variable has block-level scope. This basically means that the variable is visible only within that block of code. A block of code, in this instance, refers to a set of programs that is terminated by a loop. Look at the following example that would give an error if it was executed:

If x 0 Then
 Dim intAmount As Integer
 intAmount = 50
End If
MsgBox CStr(intAmount)

This would give an error because the value of intAmount cannot be seen outside of the block of code encompassed by the If...End If loop.

If you declare a variable inside a procedure but not within the constraints of a loop, the variable is said to have procedure-level scope. This allows us to utilize the variable within the procedure, but once you get outside of it, the variable is again invisible to the rest of the program. A nice feature of procedure-level variables is that you don't really have to worry as much about the naming of them because each procedure can name their variables exactly the same. Because you cannot see them outside of the procedure, the code does not cause a problem.

Module Level and Project Level Scope

Module-level and project-level declarations can get a little more confusing because the modules themselves are declared using one of several access modifiers (Private, Public, or Friend). Don't concern yourself with these ideas at this time, but remember that if you declare a module as a Friend, and then declare a variable as a Public inside the module, the variable takes on the attributes of the module in which it was declared and, thus, has a Friend scope.

A variable that is declared in the declarations section of a standard module using the Private access modifier has module-level scope. It is visible in the entire module, but when you are outside of the module, it is invisible to the rest of the program code. Now, if you were to create the same variable by using the Friend access modifier, the variable would be visible in the entire project (project-level scope). It is not visible to other projects, however. A third possibility exists if you declare the same variable as a Public modifier (the module would also need to be Public); the variable is visible to this project and any additional projects that reference this one.

Lifetime

Many people confuse a variable lifetime with its scope, but the differences are actually very clear. The lifetime of a variable refers to what time during program execution a variable is valid. As you know, scope refers to where the variable can be seen by other code. A static variable is a special type of variable, which has a lifetime that exists during the entire program execution. Previous versions of VB lacked this feature, although you could implement something similar using a workaround.

Constants

Constants are similar to variables, although the value that is assigned to a constant does not get changed during program execution. You can use constants instead of hard coding the values directly into your code as it's much easier to make changes to your code if you approach it in this manner.

For example, suppose you are developing an application that uses the value of pi (3.1415) for calculations. Instead of adding the value 3.1415 to every line that uses it for a calculation, you can store it in a variable. Look at the following code example:

Const X as Double = 3.1415
Dim Y as Integer
Dim Answer as Double

For Y = 1 to 100
 Answer = Const * Y
Next Y

You could have replaced Const with the actual value 3.1415 in the Answer = line. This would be very easy for such a simple example. However, suppose you use this value in 40 or 50 calculations in different modules and procedures in your code. Now, assume that you have been asked to shorten 3.1415 to 3.14 for the calculations. You could change this in a single location in your program by changing the X constant, or you could go through hundreds of lines of code searching for 3.1415. Although you could eventually change all of them, it saves a great deal of time and is much more reliable to use a constant.

Structures

Now that we have looked at declaring variables using the built-in data types, we're going to take a moment to look at the ability to create your own custom data types using a structure. A structure contains members that can be any data type. The members each have their own names, allowing you to reference them individually. The following example creates a structure called Customer:

Structure Customer
Dim ID As Long
Dim Name As String
Dim Address As String
Dim City As String
Dim State As String
End Structure

After you have created a structure, you can use it within your program. The following example gives you an idea on how to use these structures:

Dim cust as Customer

Cust.ID = 1000
Cust.Name = "Clayton Crooks"
Cust.Address = "12345 South Main Street"

These lines created a variable called cust as type Customer. We then had access to the individual members and assigned them values of 'Clayton Crooks', 1000, and '12345 South Main Street'.

Converting Between Data Types

In a project, you'll often be faced with the prospect of converting data from one format to another. For example, suppose you have an integer value that you want to store in a text box. You'll need to convert the data from an Integer to a String. The process of converting the values is known as casting, or simply conversion. A cast can be one of two distinct types: widening or narrowing. A widening cast is one that converts to a data type that can handle all of the existing data. That is, if you convert from Short to Integer, the Integer data type can handle everything that was stored in the Short data type. Therefore, no data is lost. The narrowing cast is obviously the opposite of this, in which data is lost in the conversion process.

With VB .NET, data conversions are made in one of two ways: implicitly or explicitly. An implicit conversion occurs without interaction from the developer. For example, look at the following code:

Dim X as Long
X = 99

Although the value 99 that is stored in X is obviously an Integer, it is implicitly converted to a Long for storage in the variable. VB .NET did this on its own without any interaction. Explicit conversion requires calling one of the many VB .NET conversion functions. Table 5.3 details these functions:

Table 5.3: VB .NET conversion functions and descriptions

Function

Example

Description

CBool

newValue = CBool(oldValue)

Converts any valid String or numeric expression to Boolean. If a numeric value is converted, it results in True if the value is nonzero or False if the value is zero.

CByte

newValue = CByte(oldValue)

Converts a numeric data type from 0 to 255 to a byte. Any fractions are rounded.

CChar

newValue = CChar(oldValue)

Returns the first character of a string that is passed to it.

CCur

newValue = CCur(oldValue)

Converts a data type to Currency.

CDate

newValue = CDate(oldValue)

Converts a data type to Date or Time.

CDbl

newValue = CDbl(oldValue)

Converts a data type to Double.

CInt

newValue = CInt(oldValue)

Converts a data type to Integer while rounding fractional portions.

CShort

newValue = CShort(oldValue)

Rounds any fractional part while converting to a Short.

CSng

newValue = CSng(oldValue)

Converts a data type to Single.

CStr

newValue = CStr(oldValue)

Converts a data type to String.

Arrays

When you develop applications, you're often faced with the need to store multiple instances of like data. An array is a set of variables that are represented by a single name. The individual variables are called elements and are identified from one another via an index number.

Arrays have a lower bound and an upper bound and have changed slightly in Visual Basic .NET. This is one of those areas in which VB6 programmers need to be careful. The lower bound for an array is always 0, and unlike previous versions of VB, you cannot change the lower bound. For example, suppose you have an array of 10 elements. This suggests that the lower bound is 0 and the upper bound is 9.

Declaring an array is similar to declaring other variables:

Dim Name(50) As String

This creates an array of 50 elements that are each a string. The lower bound is 0 and the upper bound is 49.

Like variables, you can also initialize the array when you declare it. The following code declares an array of integers and initializes the values.

Dim Num1(5) As Integer = {9,8,7,6,5}

Alternatively, you could also declare this as follows:

Dim Num1() As Integer = {9,8,7,6,5}

This dimensions the variable to the appropriate number of elements automatically.

You can access the individual elements of an array as you would other variables. For instance, to set the third element to 0:

Num1(3) = 0

Multidimensional Arrays

An array isn't limited to a single dimension. They can have multiple dimensions that allow you to create a grid. VB .NET can have up to 60 dimensions, although this is probably unrealistic for any real-world use. The following example gives you an idea of dimensioning an array:

Dim grid(3, 3) As Integer

To access the information in this array to retrieve or assign values, you use the combination of numbers to identify the element:

grid(0, 0) = 1
grid(1, 1) = 0

You can also declare an array with uneven elements. For example, if you want to declare an array that holds the following data:

1

2

3

4

5

1

2

3

4

5

1

2

3

4

5

You would use the following code:

Dim arr(3,5) As Integer

To initialize a multidimensional array when you declare it, you leave the parentheses empty with the exception of a comma for each additional array dimension. For example, to initialize an array, you could use something like this:

Dim arr(,) As String = {{"1", "1", "1"}, {"2", "2", "2"}}

Dynamic Arrays

In VB .NET, all arrays are dynamic. The declared size is only the initial size of the array, which can be changed as needed. (Please note that you cannot change the dimensions of an array after declaration.) To change the size of an array, you use the ReDim statement. The process of changing the size of an array is known as redimensioning. This is confusing because we've already mentioned that you cannot actually redimension an array.

  Note 

There are two functions that can help when redimensioning arrays: UBound and LBound. UBound returns the upper limit, whereas LBound returns the lower bound.

It is actually very simple to redimension an array. Let's start with an array dimensioned as follows:

Dim Nums(10, 10) As Integer

To redimension this, you can use the following:

ReDim Nums (100,100) as Integer

When you redimension an array, all of the data in it is lost. If you need the data, you can use the Preserve keyword to keep the existing data. If you use the Preserve keyword, you can only change the last coordinate:

This is OK:

ReDim Preserve Nums (10,100) as Integer

Whereas this is not:

ReDim Preserve Nums (100,100) as Integer
  Note 

In VB6, you could have an array of controls that were very similar to the arrays we've been looking at. The new changes to the event model make control arrays a thing of the past as the event model in Visual Basic .NET allows any event handler to handle events from multiple controls. For example, if you have multiple Button controls on a form (called Button1 and Button2), you could handle the click events for both of them as follows:

Private Sub MixedControls_Click(ByVal sender As System.Object, ByVal e 
As System.EventArgs) Handles Button1.Click, Button2.Click

Loops

When you develop applications in VB .NET, you need a way to manage the execution of the programs. For example, you might need to execute code a certain number of times, or you may need to check a condition to see if you should be executing the code. For both cases, we use loops.

If Then Else

If...Then...Else loops allow you to test a condition before executing a block of code. For the block of code to execute, the condition must evaluate to True. Let's take a look at an example of an If...Then statement:

Dim X as Integer

X = 0
If X < 1 Then
 X = 6
End If

This simply checks the value of X and if it is less than the value of 1, it assigns the value 6 to it. The program code execution then continues with the next step.

Another example allows us to look at the If...Then...Else statement:

Dim Cost1 As Integer
Dim Cost2 As Integer
Dim BuyIt As Boolean

Cost1 = 50
Cost2 = 75

If Cost1 < Cost2 Then
 BuyIt = False
Else If Cost2>=Cost1 Then
 BuyIt = True
End If

The previous code is a very simplistic example, but serves its purpose to show how the ElseIf statement can be added to check multiple conditions. For If...Then statements, you need to use comparison operators to check the various conditions. In the previous example, we use the less than (<), greater than (>), and equal to (=) operators. The following list details the various types of comparison operators:

  • = Equal to
  • < Less than
  • <= Less than or equal to
  • > Greater than
  • >= Greater than or equal to
  • <> Not equal to

There are two additional operators that are worth mentioning: the Is and Like operators. The Like operator is used to compare a string to a string pattern rather than an exact copy of the string, whereas the Is operator is used to compare if two object references point to the same object. When you use the Like operator, you can use wildcards for pattern matching, as shown in Table 5.4.

Table 5.4: Wildcard character pattern matches

Character

Function

?

Matches a single character

*

Matches all or none characters

#

Matches a single digit

[character list]

Matches any single character in the character list

[! CHARACTER LIST]

MATCHES ANY SINGLE CHARACTER NOT IN THE CHARACTER LIST

The Like operator gives you many options when looking for patterns in a string. By testing the result of the condition, you can return a value of True if it is found; otherwise, a value of False is returned. Table 5.5 shows a few examples.

Table 5.5: Like operator examples

Value

Operator

Condition

Result

'pqrs'

Like

'p*p'

False

'pqrs'

Like

'p*s'

True

'pqr'

Like

'p?r'

False

'pqr'

Like

'p?r'

True

'pqr'

Like

'p#r'

False

'pqr'

Like

'p#r'

True

'aQa'

Like

'a[a-z]a'

False

'aba'

Like

'a[a-z]a'

True

'aba'

Like

'a[!a-z]a'

False

'aBa'

Like

'a[!a-z]a'

True

Sometimes, a single expression in an If...Then...Else statement is not enough.You can use multiple expressions to create a single True or False value for an If...Then...Else statement.You can use the logical operators to create compound expressions that, as a whole, return a single Boolean value. Table 5.6 lists the logical operators.

You may need to test multiple conditions in an If...Then statement. VB .NET provides this functionality as well. Table 5.6 details the available operators.

Table 5.6: Logical operators

Logical Operator

Result

And

Both expressions should be True to get a True result

Not

Expression must evaluate to False for a True result

Or

Either of the expressions must be True for a True result

Xor

One expression can be True for a True result

You can combine the logical operators to create compound expressions. Table 5.7 takes a look at some examples of compound expressions.

Table 5.7: Combining logical operators to create compound expressions

Operators

Result

0=0 And 1=2

False

0=0 And 1<2

True

0<0 Or 1=2

False

0=0 Or 1=2

True

(0=0 And 1=2) Or 1=3

False

(0=0 And 1=2) Or 1<3

True

Not 1=1

False

0=0 And Not 1=2

True

0=0 Xor 1<2

False

0=0 Xor 1<2

True

Select Case

Another type of loop that is very useful is the Select Case statement, which is very similar in functionality to the If...Then statement. The Select Case is most often used as a replacement for an If...Then statement that gets too long. As an If...Then statement grows in length, it gets much more difficult to read. The Select Case statement is much easier to read as you'll see in the following example:

Select Case X
 X<= 5
 Y = 10
 X>5 And X<=10
 Y = 15
 X>10 And X<=15
 Y = 20
 X>15 And X<=20
 Y = 25
End Select

For Loops

The For loop is used when you want to execute a block of code a finite number of times. For loops are often used when you want to read or write to or from an array. For loops use a counter to keep track of the number of iterations. A Start value is the beginning value of the counter and an End value is used as the maximum value for the loop. There is also an optional Step value (default is 1) that instructs the loop how much to increment the counter during each pass of the loop. The Step value can be a negative or positive number. For example, here is a simple loop:

Dim I As Integer

For I = 1 to 100
 Q = I * I
Next I
  Note 

Another variation of the For loop is the For...Each loop. It is most often used with arrays to loop through every item in the array.

While Loops and Do Until Loops

For loops work well if you know the exact number of times you want to execute a loop beforehand. There is another loop, called the While loop, that allows you to execute code blocks without knowing the values. It executes the loop until the condition that is being tested remains True.

This loop is started with the Do While keywords. A condition is checked to see if it is True prior to each execution of the loop. A variation of the While loop is the Do Until statement, which executes until the condition is True. A third variety, known as While...Wend, is no longer available in Visual Basic .NET. Here is a quick example of a Do While Loop in VB .NET:

Dim X As Integer = 0

Do While X < 1000
 X = X + 100
Loop

This loop executes until the X value is greater than or equal to 1000 (it actually checks to see if X < 1000 and, if so, it continues). You don't always have to wait until the loop is finished before you exit it. You can use the Exit Do statement at any time. Here is an example:

Dim X As Integer = 5
Dim Y As Integer = 10

Do While X < 10
X = X+1
Y = Y + 1

 If Y > 12 Then
 Exit Do
 End If
Loop

Basics of Functions and Procedures

Functions and procedures are blocks of code that can be called at any time in an application. They typically perform a set type of function that is useful to the application. For example, you could have a function that calculates the square root of a number. You would then call this function whenever you needed to perform this calculation. We use functions and procedure throughout the book, so we'll go over a few simple examples now:

Function LessThan500(ByVal num as Integer) As Boolean
 If num<500 Then
 Return True
 Else
 Return False
 End If
End Function

This function returns a Boolean value of True or False depending on if the value of the number that is passed to the function is less than 500. To call this function in your own program, you can do so like any of the built-in varieties. For example, you could use a variable to pass it like this:

Dim LT500 As Boolean
Dim X As Integer

X = 10
LT500 = LessThan500(X)

This passes the value of 10, and because it is less than 500, it assigns True to the value of LT500.

Another way to return a value from a function is to assign the function name itself to a value. Using the same previous example, notice the lack of the word 'Return':

Function LessThan500(ByVal num as Integer) As Boolean
 If num<500 Then
 LessThan500 = True
 Else
 LessThan500 False
 End If
End Function

You can use the method that is easier for you.

There is a big difference in how parameters are passed to functions from the earlier versions of VB. In the previous versions of Visual Basic, parameters were passed by reference by default. In Visual Basic .NET, parameters are passed by value by default.

At first, this might not seem like a big difference, but it can be in your VB .NET applications. If a parameter is passed by value, any changes made to the value occur only within the function and the rest of the code in the application doesn't see them. On the other hand, if a parameter is passed by reference, if changes are made to the value, the change is seen by the rest of your program.

Sub procedures are similar to functions but they do not return any values. You call them exactly the same as you would a function, such as:

somproc(10)

You can create a simple Sub procedure just as you would a function:

Sub somproc(ByVal x as Integer)
If x > 5 then 
 Temp = 5
Else
 Temp = 10
End Sub

You'll notice that it looks almost identical to the previous example of a function with the exception of returning a value.

Summary

In this chapter, we covered a great deal of basic information about VB .NET. We began with variables and then moved on to constants, structures, and the CTS. We created several examples of declaring variables and constants. After these topics, we moved our attention to arrays and showed you how to use them. Lastly, we looked at several varieties of loops and then briefly touched on functions and procedures. In Chapter 6, Object-Oriented Programming with VB .NET, we look at what is arguably the most important new feature of VB .NET: its object-oriented techniques.



Developing Tablet PC Applications
Developing Tablet PC Applications (Charles River Media Programming)
ISBN: 1584502525
EAN: 2147483647
Year: 2003
Pages: 191

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net