Chapter 3. Writing Software

Provided by: Thearon Willis, Bryan Newsome

Beginning Microsoft Visual Basic 2008

This topic contains the following sections.

  • Information and Data
  • Working with Variables
  • Comments and Whitespace
  • Data Types
  • Storing Variables
  • Methods
  • Summary
  • Exercises

Now that you have Visual Basic 2008 up and running and even written a simple program, you’re going to look at the fundamentals behind the process of writing software and start putting together some exciting programs of your own.

In this chapter, you will:

  • Learn about algorithms

  • Learn to use variables

  • Explore different data types, including integers, floating-point numbers, strings, and dates

  • Study scope

  • Learn about debugging applications

  • Learn more about how computers store data in memory

Information and Data

Information describes facts and can be presented or found in any format, whether that format is optimized for humans or for computers. For example, if you send four people to different intersections to survey traffic, at the end of the process you will end up with four handwritten tallies of the number of cars that went past (say, a tally for each hour).

The term data is used to describe information that has been collated, ordered, and formatted in such a way that it can be used by a piece of computer software. The information you have (several notebooks full of handwritten scribbles) cannot be directly used by a piece of software. Rather, someone has to work with it to convert it into usable data the computer can understand. For example, the scribbles can be transferred to an Excel spreadsheet that can be directly used by a piece of software designed to analyze the results.

Algorithms

The computer industry changes at an incredible speed. Most professionals constantly retrain and re-educate themselves to keep their skills sharp and up-to-date. However, some aspects of computing haven’t really changed since they were first invented and perhaps won’t change within our lifetimes. The process and discipline of software development is a good example of an aspect of computer technology whose essential nature hasn’t changed since the beginning.

For software to work, you need to have some data to work with. The software then takes this data and manipulates it into another form. For example, software may take your customer database stored as ones and zeros on your computer’s hard drive and make it available for you to read on your computer’s monitor. The on-board computer in your car constantly examines environmental and performance information and continually adjusts the fuel mix to make the car run more efficiently. Your telephone service provider records the phone number of each call and the length of the call that you make and generates bills based on this information.

The base underpinning of all software is the algorithm. Before you can write software to solve a problem, you have to break it down into a step-by-step description of how the problem is going to be solved. An algorithm is independent of the programming language, so, if you like, you can describe it to yourself either as a spoken language, with diagrams, or with whatever helps you visualize the problem.

Imagine that you work for a wireless telephone company and need to produce bills based on calls that your customers make. Here’s an algorithm that describes a possible solution:

  1. On the first day of the month, you need to produce a bill for each customer you have.

  2. For each customer, you have a list of calls that the customer has made in the previous month.

  3. You know the duration of each call, and the time of day when the call was made. Based on this information, you can determine the cost of each call.

  4. For each bill, you total the cost of each call.

  5. If a customer exceeds a preset time limit, you charge the customer a certain rate for each minute that exceeds the allotted time.

  6. You apply sales tax to each bill.

  7. After you have the final bill, you need to print it and mail it.

Those seven points describe, fairly completely, an algorithm for a piece of software that generates bills for a wireless telephone company. At the end of the day, it doesn’t matter whether you build this solution in C++, Visual Basic 2008, C#, Java, or whatever—the basic algorithms of the software never change. (However, it’s important to realize that each of those seven parts of the algorithm may well be made up of smaller, more detailed algorithms.)

The good news for a newcomer to programming is that algorithms are usually easy to construct. There shouldn’t be anything in the preceding algorithm that you don’t understand. Algorithms always follow common-sense reasoning, although you may have to code algorithms that contain complex mathematical or scientific reasoning. It may not seem like common sense to you, but it will to someone else! The bad news is that the process of turning the algorithm into code can be arduous. As a programmer, learning how to construct algorithms is the most important skill you will ever obtain.

All good programmers respect the fact that the preferred language of the programmer is largely irrelevant. Different languages are good at doing different things. C++ gives the developer a lot of control over the way a program works; however, it’s harder to write software in C++ than it is in Visual Basic 2008. Likewise, building the user interface for desktop applications is far easier to do in Visual Basic 2008 than it is in C++. (Some of these problems do go away when you use managed C++ with .NET, so this statement is less true today than it was years ago.) What you need to learn to do as a programmer is to adapt different languages to achieve solutions to a problem in the best possible way. Although when you begin programming you’ll be hooked on one language, remember that different languages are focused toward developing different kinds of solutions. At some point, you may have to take your basic skills as an algorithm designer and coder to a new language.

What Is a Programming Language?

A programming language is anything capable of making a decision. Computers are very good at making decisions, but they have to be fairly basic, for example: “Is this number greater than three?” or “Is this car blue?”

If you have a complicated decision to make, the process of making that decision has to be broken down into simple parts that the computer can understand. You use algorithms to determine how to break down a complicated decision into simpler ones.

A good example of a problem that’s hard for a computer to solve is recognizing peoples’ faces. You can’t just say to a computer, “Is this a picture of Dave?” Instead, you have to break the question down into a series of simpler questions that the computer can understand.

The decisions that you ask computers to make will have one of two possible answers: yes or no. These possibilities are also referred to as true and false and also as 1 and 0. In software terms, you cannot make a decision based on the question, “How much bigger is 10 compared to 4?” Instead, you have to make a decision based on the question, “Is 10 bigger than 4?” The difference is subtle, yet important—the first question does not yield an answer of yes or no, whereas the second question does. Of course, a computer is more than capable of answering the first question, but this is actually done through an operation; in other words, you have to actually subtract 4 from 10 to use the result in some other part of your algorithm.

You might be looking at the requirement for yes/no answers as a limitation, but it isn’t really. Even in our everyday lives the decisions we make are of the same kind. Whenever you decide something, you accept (yes, true, 1) something and reject (no, false, 0) something else.

You are using Visual Basic 2008 for a language, but the important aspects of programming are largely language independent of the language. Understanding that any software, no matter how flashy it is, or which language it is written in, is made up of methods (functions and subroutines: the lines of code that actually implement the algorithm) and variables (place holders for the data the methods manipulate) is key.

Working with Variables

A variable is something that you store a value in as you work through your algorithm. You can then make a decision based on that value (for example, “Is it equal to 7?” or “Is it more than 4?”), or you can perform operations on that value to change it into something else (for example, “Add 2 to the value”, “Multiply it by 6”, and so on).

Before you get bogged down in code, take a moment to look at another algorithm:

  1. Create a variable called intNumber and store in it the value 27.

  2. Add 1 to the value of the variable called intNumber and store the new value in the same variable.

  3. Display the value of the variable called intNumber to the user.

This algorithm, creates a variable called intNumber and stores in it the value 27. This means that there’s a part of the computer’s memory that is being used by the program to store the value 27. That piece of memory keeps storing that value until you change it or tell the program that you don’t need it any more.

In the second step, an add operation is performed. You’re taking the value contained in intNumber and adding 1 to its value. After you’ve performed this operation, the piece of memory given over to storing intNumber contains the value 28.

In the final point, you want to tell the user what the value of intNumber is. So you read the current value from memory and write it out to the screen.

Again, there’s nothing about the algorithm there that you can’t understand. It’s just common sense! However, the Visual Basic 2008 code looks a little more cryptic. In the following Try It Out, you learn more about working with variables first hand.

  1. Create a new project in Visual Studio 2008 by selecting File New Project from the menu bar. In the New Project dialog box, select Windows Forms Application from the right-hand pane and enter the project name as Variables and click OK (see Figure 3–1).

New Project -> Visual Basic -> Windows Forms App..

Figure 3–1

  1. Make Form1 a little smaller and add a Button control from the Toolbox to it. Set the button’s Text property to Add 1 to intNumber and its Name property to btnAdd. Your form should look similar Figure 3–2.

Form1

Figure 3–2

  1. Double-click the button to open the btnAdd_Click event handler. Add the following highlighted code to it:

    Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click Dim intNumber As Integer intNumber = 27 intNumber = intNumber + 1 MessageBox.Show("Value of intNumber + 1 = " & intNumber.ToString, _ "Variables") End Sub

  2. Click the Save All button on the toolbar, verify the information in the Save Project dialog box, and then click the Save button to save your project.

  3. Run the project, click the Add 1 to intNumber button, and you’ll see a message box like the one in Figure 3–3.

Variables

Figure 3–3

Tip

The program starts at the top and works its way down, one line at a time, to the bottom. The first line defines a new variable, called intNumber:

Dim intNumber As Integer

Dim is a keyword. As stated in Chapter 1, a keyword has a special meaning in Visual Basic 2008 and is used for things such as commands. Dim tells Visual Basic 2008 that what follows is a variable definition.

Its curious name harks back to the original versions of the BASIC language. BASIC has always needed to know how much space to reserve for an array (discussed in Chapter 5), so it had a command to tell it the dimensions of the array—Dim for short. Visual Basic extends that command to all other kinds of variables as well to mean make some space for in general.

The variable name comes next and is intNumber. Note that the variable name uses the Modified Hungarian notation discussed in Chapter 1. In this case the prefix int is short for Integer, which represents the data type for this variable, as described in the following paragraph. Then a name was chosen for this variable; in this case the name is Number. Whenever you see this variable throughout your code, you know that this variable will represent a number that is of the Integer data type.

As Integer tells Visual Basic 2008 what kind of value you want to store in the variable. This is known as the data type. For now, all you need to know is that this is used to tell Visual Basic 2008 that you expect to store an integer (whole number) value in the variable.

The next line sets the value of intNumber:

intNumber = 27

In other words, it stores the value 27 in the variable intNumber.

The next statement simply adds 1 to the variable intNumber:

intNumber = intNumber + 1

What this line actually means is: Keep the current value of intNumber and add 1 to it.

The final line displays a message box with the text Value of intNumber + 1 = and the current value of intNumber. You’ve also set the title of the message box to Variables to match the project name. When using numeric variables in text, it is a good idea to use the ToString method to cast the numeric value to a string. This prevents the compiler from having to figure out that this is a number and then converting that number to a string so it can be displayed:

MessageBox.Show("Value of intNumber + 1 = " & intNumber.ToString, _ "Variables")

Comments and Whitespace

When writing software code, you must be aware that you or someone else may have to change that code in the future. Therefore, you should try to make it as easy to understand as possible.

Comments

Comments are parts of a program that are ignored by the Visual Basic 2008 compiler, which means you can write whatever you like in them, be it English, C#, Perl, FORTRAN, Chinese, whatever. What they’re supposed to do is help the human developer reading the code understand what each part of the code is supposed to be doing.

All languages support comments, not just Visual Basic 2008. If you’re looking at C# code, for example, you’ll find that comments start with a double forward slash (//).

What’s a good way of knowing when you need a comment? Well, it’s different for different situations, but a good rule of thumb is to think about the algorithm. The program in the previous Try It Out exercise had this algorithm:

  1. Define a value for intNumber.

  2. Add 1 to the value of intNumber.

  3. Display the new value of intNumber to the user.

You can add comments to the code from that example to match the steps in the algorithm:

'Define a variable for intNumber Dim intNumber As Integer 'Set the initial value intNumber = 27 'Add 1 to the value of intNumber intNumber = intNumber + 1 'Display the new value of intNumber MessageBox.Show("Value of intNumber + 1 = " & intNumber.ToString, _ "Variables")

In Visual Basic 2008, you begin your comments with an apostrophe (‘). Anything on the same line following that apostrophe is your comment. You can also add comments onto a line that already has code, like this:

intNumber = intNumber + 1 'Add 1 to the value of intNumber

This works just as well, because only comments (not code) follow the apostrophe. Note that the comments in the preceding code, more or less, match the algorithm. A good technique for adding comments is to write a few words explaining the stage of the algorithm that’s being expressed as software code.

You can also use the built-in XML Documentation Comment feature of Visual Studio 2008 to create comment blocks for your methods. To use this feature, place your cursor on the blank line preceding your method definition and type three consecutive apostrophes. The comment block is automatically inserted as shown in the code here.

''' <summary> ''' ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click

What’s really cool about this feature is that Visual Studio 2008 automatically fills in the name values of the parameters in the comment block based on the parameters defined in your method. If your method does not have any parameters, the <param> tag will not be inserted into the comment block.

Once a comment block has been inserted, you can provide a summary of what the method does and any special remarks that may need to be noted before this method is called or any other special requirements of the method. If the method returns a value, then a <returns> tag will also be inserted, and you can insert the return value and description.

Comments are primarily used to make the code easier to understand, either to a new developer who’s never seen your code before or to you when you haven’t reviewed your code for a while. The purpose of a comment is to point out something that might not be immediately obvious or to summarize code to enable the developer to understand what’s going on without having to ponder each and every line.

You’ll find that programmers have their own guidelines about how to write comments. If you work for a larger software company, or your manager/mentor is hot on coding standards, they’ll dictate which formats your comments should take and where you should and should not add comments to the code.

Whitespace

Another important aspect of writing readable code is to leave lots of whitespace. Whitespace (space on the screen or page not occupied by characters) makes code easier to read, just as spaces do in English. In the previous example, there is a blank line before each comment. This implies to anyone reading the code that each block is a unit of work, which it is.

You’ll be coming back to the idea of whitespace in the next chapter, which discusses controlling the flow through your programs using special code blocks, but you’ll find that the use of whitespace varies between developers. For now, remember not to be afraid to space out your code—it’ll greatly improve the readability of your programs, especially as you write long chunks of code.

The compiler ignores whitespace and comments, so there are no performance differences between code with lots of whitespace and comments, and code with none.

Data Types

When you use variables, it’s a good idea to know ahead of time the things that you want to store in them. So far in this chapter, you’ve seen a variable that holds an integer number.

When you define a variable, you must tell Visual Basic 2008 the type of data that should be stored in it. As you might have guessed, this is known as the data type, and all meaningful programming languages have a vast array of different data types to choose from. The data type of a variable has a great impact on how the computer will run your code. In this section, you’ll take a deeper look at how variables work and how their types affect the performance of your program.

Working with Numbers

When you work with numbers in Visual Basic 2008, you’ll be working with two kinds of numbers: integers and floating-point numbers. Both have very specific uses. Integers are usually not much use for calculations of quantities, for example, calculating how much money you have left on your mortgage or calculating how long it would take to fill a swimming pool with water. For these kinds of calculations, you’re more likely to use floating-point variables because they can be used to represent numbers with fractional parts, whereas integer variables can hold only whole numbers.

On the other hand, oddly, you’ll find that in your day-to-day activities you’re far more likely to use integer variables than floating-point variables. Most of the software that you write will use numbers to keep track of what is going on by counting, rather than to calculate quantities.

For example, suppose you are writing a program that displays customer details on the screen. Furthermore, suppose you have 100 customers in your database. When the program starts, you’ll display the first customer on the screen. You also need to keep track of which customer is being displayed, so that when the user says, “Next, please,” you’ll actually know which one is next.

Because a computer is more comfortable working with numbers than with anything else, you’ll usually find that each customer has been given a unique number. This unique number will, in most cases, be an integer. What this means is that each of your customers will have a unique integer number between 1 and 100 assigned to them. In your program, you’ll also have a variable that stores the ID of the customer that you’re currently looking at. When the user asks to see the next customer, you add one to that ID (a.k.a. increment by one) and display the new customer.

You’ll see how this works as you move on to more advanced topics, but for now, rest assured that you’re more likely to use integers than floating-point numbers. Take a look now at some common operations.

Common Integer Math Operations

In this section, you create a new project for your math operations.

  1. Create a new project in Visual Studio 2008 by selecting File New Project from the menu. In the New Project dialog box, select Windows Forms Application from the right pane (refer to Figure 3–1), and enter the project name as Integer Math and click OK.

  2. Using the Toolbox, add a new Button control to Form1 as before. Set its Name property to btnIntMath and its Text property to Math Test. Double-click it and add the following highlighted code to the new Click event handler that will be created:

    Private Sub btnIntMath_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnIntMath.Click

    'Declare variable
            Dim intNumber As Integer
    
            'Set number, add numbers, and display results
            intNumber = 16
            intNumber = intNumber + 8
            MessageBox.Show("Addition test.. " & intNumber.ToString, _
                "Integer Math")
    
            'Set number, subtract numbers, and display results
            intNumber = 24
            intNumber = intNumber—2
            MessageBox.Show("Subtraction test.. " & intNumber.ToString, _
                "Integer Math")
    
            'Set number, multiply numbers, and display results
            intNumber = 6
            intNumber = intNumber * 10
            MessageBox.Show("Multiplication test.. " & intNumber.ToString, _
                "Integer Math")
    
            'Set number, divide numbers, and display results
            intNumber = 12
            intNumber = CType(intNumber / 6, Integer)
            MessageBox.Show("Division test.. " & intNumber.ToString, _
                "Integer Math")
    

    End Sub

  3. Save your project by clicking the Save All button on the toolbar.

  4. Run the project and click the Math Test button. You’ll be able to click through four message box dialog boxes, as shown in Figure 3–4.

Integer Math

Figure 3–4

Tip

None of the code you’ve seen should be too baffling. You’ve already seen the addition operator before. Here it is again:

'Set number, add numbers, and display results intNumber = 16 intNumber = intNumber + 8 MessageBox.Show("Addition test.. " & intNumber.ToString, _ "Integer Math")

So, all you’re saying is this:

  1. Let intNumber be equal to the value of 16.

  2. Then, let intNumber be equal to the current value of intNumber (which is 16) plus 8.

As you can see from the message dialog box shown in Figure 3–4, you get a result of 24, which is correct.

The subtraction operator is a minus (–) sign. Here it is in action:

'Set number, subtract numbers, and display results intNumber = 24 intNumber = intNumber—2 MessageBox.Show("Subtraction test.. " & intNumber.ToString, _ "Integer Math")

Again, same deal as before:

  1. Let intNumber be equal to the value 24.

  2. Let intNumber be equal to the current value of intNumber (which is 24) minus 2.

The multiplication operator is an asterisk (*). Here it is in action:

'Set number, multiply numbers, and display results intNumber = 6 intNumber = intNumber * 10 MessageBox.Show("Multiplication test.. " & intNumber.ToString, _ "Integer Math")

Here your algorithm states:

  1. Let intNumber be equal to the value 6.

  2. Let intNumber be equal to the current value of intNumber (which is 6) times 10.

Finally, the division operator is a forward slash (/). Here it is in action:

'Set number, divide numbers, and display results intNumber = 12 intNumber = CType(intNumber / 6, Integer) MessageBox.Show("Division test.. " & intNumber.ToString, _ "Integer Math")

Again, all you’re saying is:

  1. Let intNumber be equal to the value of 12.

  2. Let intNumber be equal to the current value of intNumber (which is 12) divided by 6.

The division of intNumber by the value of 6 has been enclosed in the CType function. The CType function returns the result of explicitly converting an expression to a specified data type, which in this case is an Integer number as indicated by the Integer type name. Because the division of two numbers could result in a floating-point number, you should use the CType function to force the results to an integer number.

This explicit conversion is not necessary when the Option Strict setting is set to Off but is required when this setting is set to On. The Option Strict setting ensures compile-time notification of narrowing conversion of numeric operations so they can be avoided and prevent run-time errors.

To access the settings for Option Strict, click the Tools menu in Visual Studio 2008 and then click the Options menu item. In the Options dialog box, expand the Projects and Solutions node and then click VB Defaults. From here you can turn the Option Strict setting on and off.

Integer Math Shorthand

In the next Try It Out, you’ll see how you can perform the same operations without having to write as much code by using shorthand operators (assignment operators). Although they look a little less logical than their more verbose counterparts, you’ll soon learn to love them.

  1. Go back to Visual Studio 2008 and open the code for Form1.vb again. Change the highlighted lines:

    Private Sub btnIntMath_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnIntMath.Click 'Declare variable Dim intNumber As Integer 'Set number, add numbers, and display results intNumber = 16 intNumber += 8

    MessageBox.Show("Addition test.. " & intNumber.ToString, _ "Integer Math") 'Set number, subtract numbers, and display results intNumber = 24 intNumber -= 2 MessageBox.Show("Subtraction test.. " & intNumber.ToString, _ "Integer Math") 'Set number, multiply numbers, and display results intNumber = 6 intNumber *= 10

    MessageBox.Show("Multiplication test.. " & intNumber.ToString, _ "Integer Math") 'Set number, divide numbers, and display results intNumber = 12 intNumber = CType(intNumber / 6, Integer) MessageBox.Show("Division test.. " & intNumber.ToString, _ "Integer Math") End Sub

  2. Run the project and click the Math Test button. You’ll get the same results as in the previous Try It Out exercise.

Tip

To use the shorthand version you just drop the last intNumber variable and move the operator to the left of the equals sign. Here is the old version:

intNumber = intNumber + 8

. . . and here’s the new version:

intNumber += 8

The Problem with Integer Math

The main problem with integer math is that you can’t do anything that involves a number with a fractional part. For example, you can’t do this:

'Try multiplying numbers.. intNumber = 6 intNumber = intNumber * 10.23

Or, rather, you can actually run that code, but you won’t get the result you were expecting. Because intNumber has been defined as a variable designed to accept an integer only; the result is rounded up or down to the nearest integer. In this case, although the actual answer is 61.38, intNumber will be set to the value 61. If the answer were 61.73, intNumber would be set to 62.

With the Option Strict setting set to On, the preceding code would produce an error in the IDE and the program would not compile. With the Option Strict setting set to Off, this code is allowed.

A similar problem occurs with division. Here’s another piece of code:

'Try dividing numbers..intNumber = 12 intNumber = intNumber / 7

This time the answer is 1.71. However, because the result has to be rounded up in order for it to be stored in intNumber, you end up with intNumber being set equal to 2. As you can imagine, if you were trying to write programs that actually calculated some form of value, you’d be in big trouble, as every step in the calculation would be subject to rounding errors.

In the next section, you’ll look at how you can do these kinds of operations with floating-point numbers.

Floating-Point Math

You know that integers are not good for most mathematical calculations because most calculations of these types involve a fractional component of some quantity. Later in this chapter, you’ll see how to use floating-point numbers to calculate the area of a circle. In the following Try It Out, we’ll introduce the concepts.

  1. Create a new Windows Forms Application project in Visual Studio 2008 called Floating Point Math. As before, place a button on the form, setting its name to btnFloatMath and its text to Double Test.

  2. Double-click btnFloatMath and add the following highlighted code:

    Private Sub btnFloatMath_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnFloatMath.Click'Delcare variable Dim dblNumber As Double 'Set number, multiply numbers, and display results dblNumber = 45.34 dblNumber *= 4.333 MessageBox.Show("Multiplication test.. " & dblNumber.ToString, _ "Floating Points") 'Set number, divide numbers, and display results dblNumber = 12 dblNumber /= 7 MessageBox.Show("Division test.. " & dblNumber.ToString, _ "Floating Points") End Sub

  3. Save your project by clicking the Save All button on the toolbar.

  4. Run the project and you’ll see the results shown in Figure 3–5.

Floating Points

Figure 3–5

Tip

Perhaps the most important change in this code is the way you’re defining your variable:

'Declare variable Dim dblNumber As Double

Rather than saying As Integer at the end, you’re saying As Double. This tells Visual Basic 2008 that you want to create a variable that holds a double-precision floating-point number, rather than an integer number. This means that any operation performed on dblNumber will be a floating-point operation, rather than an integer operation. Also note that you have used a different Modified Hungarian notation prefix to signify that this variable contains a number that is of the Double data type.

However, there’s no difference in the way either of these operations is performed. Here, you set dblNumber to be a decimal number and then multiply it by another decimal number:

'Set number, multiply numbers, and display results dblNumber = 45.34 dblNumber *= 4.333 MessageBox.Show("Multiplication test.. " & dblNumber.ToString, _ "Floating Points")

When you run this, you get a result of 196.45822, which, as you can see, has a decimal component, and therefore you can use this in calculations.

Of course, floating-point numbers don’t have to have an explicit decimal component:

'Set number, divide numbers, and display results dblNumber = 12 dblNumber /= 7 MessageBox.Show("Division test.. " & dblNumber.ToString, _ "Floating Points")

This result still yields a floating-point result, because dblNumber has been set up to hold such a result. You can see this by your result of 1.71428571428571, which is the same result you were looking for when you were examining integer math.

This time, the code allows you to use the math shorthand to divide two numbers as the variable that holds the results will accept a floating-point number. Thus you do not have to use the CType function to convert the results to an integer value.

A floating-point number gets its name because it is stored like a number written in scientific notation on paper. In scientific notation, the number is given as a power of 10 and a number between 1 and 10 that is multiplied by that power of 10 to get the original number. For example, 10,001 is written 1.0001 × 104, and 0.0010001 is written 1.0001 × 10–3. The decimal point “floats” to the position after the first digit in both cases. The advantage is that large numbers and small numbers are represented with the same degree of precision (in this example, one part in 10,000). A floating-point variable is stored in the same way inside the computer, but in base two instead of base 10 (see “Storing Variables,” later in this section).

Other States

Floating-point variables can hold a few other values besides decimal numbers. Specifically, these are:

  • NaN—which means not a number

  • Positive infinity

  • Negative infinity

We won’t show how to get all of the results here, but the mathematicians among you will recognize that .NET caters to your advanced math needs.

Single-Precision Floating-Point Numbers

We’ve been saying “double-precision floating-point.” In .NET, there are two main ways to represent floating-point numbers, depending on your needs. In certain cases the decimal fractional components of numbers can zoom off to infinity (pi being a particularly obvious example), but the computer does not have an infinite amount of space to hold digits, so there has to be some limit at which the computer stops keeping track of the digits to the right of the decimal point. The limit is related to the size of the variable, which is a subject discussed in much more detail toward the end of this chapter. There are also limits on how large the component to the left of the decimal point can be.

A double-precision floating-point number can hold any value between –1.7 × 10308 and + 1.7 × 10308 to a great level of accuracy (one penny in 45 trillion dollars). A single-precision floating-point number can only hold between –3.4 × 1038 and +3.4 × 1038. Again, this is still a pretty huge number, but it holds decimal components to a lesser degree of accuracy (one penny in only $330,000)—the benefits being that single-precision floating-point numbers require less memory and calculations involving them are faster on some computers.

You should avoid using double-precision numbers unless you actually require more accuracy than the single-precision type allows. This is especially important in very large applications, where using double-precision numbers for variables that only require single-precision numbers could slow your program significantly.

The calculations you’re trying to perform will dictate which type of floating-point number you should use. If you want to use a single-precision number, use As Single rather than As Double, like this:

Dim sngNumber As Single

Working with Strings

A string is a sequence of characters, and you use double quotes to mark its beginning and end. You’ve seen how to use strings to display the results of simple programs on the screen. Strings are commonly used for exactly this function—telling the user what happened and what needs to happen next. Another common use is storing a piece of text for later use in an algorithm. You’ll see lots of strings throughout the rest of the book. So far, you’ve used strings like this:

MessageBox.Show("Multiplication test.. " & dblNumber.ToString, _ "Floating Points")

"Multiplication test.." and "Floating Points" are strings; you can tell because of the double quotes ("). However, what about dblNumber? The value contained within dblNumber is being converted to a string value that can be displayed on the screen by use of the ToString method of the Double class, which defines the variable type. For example, if dblNumber represents the value 27, to display it on the screen it has to be converted into a quoted string two characters in length, and this is what the ToString method does. In the next Try It Out, you look at some of the things you can do with strings.

  1. Create a new Windows Forms Application using the File New Project menu option. Call it Strings.

  2. Using the Toolbox, draw a button with the Name property btnStrings on the form and set its Text property to Using Strings. Double-click it and then add the highlighted code:

    Private Sub btnStrings_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnStrings.Click 'Declare variable Dim strResults As String 'Set the string value strResults = "Hello World!" 'Display the results MessageBox.Show(strResults, "Strings") End Sub

  3. Save your project by clicking the Save All button on the toolbar.

  4. Run the project and click the Using Strings button. You’ll see a message like the one in Figure 3–6.

Strings

Figure 3–6

Tip

You can define a variable that holds a string using a similar notation to that used with the number variables, but this time using As String:

'Declare variable Dim strResults As String

You can also set that string to have a value, again as before:

'Set the string value strResults = "Hello World!"

You need to use double quotes around the string value to delimit the string, meaning to mark where the string begins and where the string ends. This is an important point, because these double quotes tell the Visual Basic 2008 compiler not to try to compile the text that is contained within the string. If you don’t include the quotes, Visual Basic 2008 treats the value stored in the variable as part of the program’s code, tries to compile it and can’t, causing the whole program to fail to compile.

With the value Hello World! stored in a string variable called strResults, you can pass that variable to the message box whose job it is to extract the value from the variable and display it. So, you can see that strings can be defined and used in the same way as the numeric values you saw before. Now look at how to perform operations on strings.

Concatenation

Concatenation means linking things together in a chain or series; to join them. If you have two strings that you join together, one after the other, you say they are concatenated. You can think of concatenation as addition for strings. In the next Try It Out, you work with concatenation.

  1. Using the same Strings project, view the Designer for Form1 and add a new button. Set its Name property to btnConcatenation and its Text property to Concatenation. Double-click the button and add the following highlighted code:

    Private Sub btnConcatenation_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnConcatenation.Click 'Declare variables Dim strResults As String Dim strOne As String Dim strTwo As String 'Set the string values strOne = "Hello" strTwo = " World!" 'Concatenate the strings strResults = strOne & strTwo 'Display the results MessageBox.Show(strResults, "Strings") End Sub

  2. Run the project and click the Concatenation button. You’ll see the same results that were shown in Figure 3–6.

Tip

In this Try It Out, you start by declaring three variables that are String data types:

'Declare variables Dim strOne As String Dim strTwo As String Dim strResults As String

Then you set the values of the first two strings.

'Set the string values strOne = "Hello" strTwo = " World!"

After you’ve set the values of the first two strings, you use the & operator to concatenate the two previous strings, setting the results of the concatenation in a new string variable called strResults:

'Concatenate the strings strResults = strOne & strTwo

What you’re saying here is, “Let strResults be equal to the current value of strOne followed by the current value of strTwo.” By the time you call MessageBox.Show, strResults will be equal to "Hello World!", so you get the same value as before.

'Display the results MessageBox.Show(strResults, "Strings")

Using the Concatenation Operator Inline

You don’t have to define variables to use the concatenation operator. You can use it on the fly, as you saw in the Floating-Point Math, Integer Math, and Variables projects. You’ve already seen the concatenation operator being used like this in previous examples. What this is actually doing is converting the value stored in dblNumber to a string so that it can be displayed on the screen. Look at this code:

MessageBox.Show("Division test.. " & dblNumber.ToString, _ "Floating Points")

The portion that reads, "Division test.. " is actually a string, but you don’t have to define it as a string variable. In Visual Basic 2008 parlance, this is called a string literal, meaning that it’s exactly as shown in the code and doesn’t change. When you use the concatenation operator on this string together with dblNumber.ToString, the value contained in the dblNumber variable is converted into a string and tacked onto the end of "Division test.. ". Remember that the ToString method converts the value contained in a variable to a string value. The result is one string that is passed to MessageBox.Show and that contains both the base text and the current value of dblNumber.

More String Operations

You can do plenty more with strings! Take a look at some examples in the next Try It Out. The first thing you’ll do is look at a property of the string that can be used to return its length.

  1. Using the Strings project, return to the designer for Form1. Add a TextBox control to the form and set its Name property to txtString. Add another Button control and set its Name property to btnLength and its Text property to Length. Rearrange the controls so that they look like Figure 3–7:

Form1

Figure 3–7

  1. Double-click the Length button to open its Click event handler. Add the following highlighted code:

    Private Sub btnLength_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLength.Click 'Declare variable Dim strResults As String 'Get the text from the TextBox strResults = txtString.Text 'Display the length of the string MessageBox.Show(strResults.Length.ToString & " characters(s)", _ "Strings") End Sub

  2. Run the project and enter some text into the text box.

  3. Click the Length button and you’ll see results similar to those shown in Figure 3–8.

Strings

Figure 3–8

Tip

The first thing that you do is to declare a variable to contain string data. Then you extract the text from the text box and store it in your string variable called strResults:

'Declare variable Dim strResults As String 'Get the text from the TextBox strResults = txtString.Text

When you have the string, you can use the Length property to get an integer value that represents the number of characters in it. Remember, as far as a computer is concerned, characters include things like spaces and other punctuation marks. Since the Length property returns the number of characters as an Integer data type you want to convert that number to a string using the ToString method:

'Display the length of the string MessageBox.Show(strResults.Length.ToString & " characters(s)", _ "Strings")

Substrings

Common ways to manipulate strings in a program include using a set of characters that appears at the start, a set that appears at the end, or a set that appears somewhere in between. These are known as substrings.

In the following Try It Out, you build on your previous application and get it to display the first three, middle three, and last three characters.

  1. Using the Strings project, return to the designer for Form1. Add another Button control to Form1 and set its Name property to btnSubStrings and its Text property to SubStrings. Double-click the button and add the code highlighted here:

    Private Sub btnSubStrings_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSubStrings.Click'Declare variable Dim strResults As String 'Get the text from the TextBox strResults = txtString.Text 'Display the first three characters MessageBox.Show(strResults.Substring(0, 3), "Strings") 'Display the middle three characters MessageBox.Show(strResults.Substring(3, 3), "Strings") 'Display the last three characters MessageBox.Show(strResults.Substring(strResults.Length—3), "Strings") End Sub

  2. Run the project. Enter the word Cranberry in the text box.

  3. Click the Split button and you’ll see three message boxes one after another as shown in Figure 3–9.

Strings: Cra nbe rry

Figure 3–9

Tip

The Substring method lets you grab a set of characters from any position in the string. The method can be used in one of two ways. The first way is to give it a starting point and a number of characters to grab. In the first instance, you’re telling it to start at character position 0—the beginning of the string—and grab three characters:

'Display the first three characters MessageBox.Show(strResults.Substring(0, 3), "Strings")

In the next instance, you to start three characters in from the start and grab three characters:

'Display the middle three characters MessageBox.Show(strResults.Substring(3, 3), "Strings")

In the final instance, you’re providing only one parameter. This tells the Substring method to start at the given position and grab everything right up to the end. In this case, you’re using the Substring method in combination with the Length method, so you’re saying, “Grab everything from three characters in from the right of the string to the end.”

'Display the last three characters MessageBox.Show(strResults.Substring(strResults.Length—3), "Strings")

Formatting Strings

Often when working with numbers, you’ll need to alter the way they are displayed as a string. Figure 3–5 shows how a division operator works. In this case, you don’t really need to see 14 decimal places—two or three would be fine! What you need is to format the string so that you see everything to the left of the decimal point, but only three digits to the right, which is what you do in the next Try It Out.

  1. Open the Floating-Point Math project that you created earlier in this chapter.

  2. Open the Code Editor for Form1 and make the following changes:

    'Set number, divide numbers, and display results dblNumber = 12 dblNumber /= 7

            'Display the results without formatting
            MessageBox.Show("Division test without formatting.. " & _
                dblNumber.ToString, "Floating Points")
    
            'Display the results with formatting
            MessageBox.Show("Division test with formatting.. " & _
                String.Format("{0:n3}", dblNumber), "Floating Points")
    

    End Sub

  3. Run the project. After the message box dialog box for the multiplication test is displayed you’ll see two more message boxes as shown in Figure 3–10.

Floating Points

Figure 3–10

Tip

The magic here is in the call to String.Format. This powerful method allows the formatting of numbers. The key is all in the first parameter, as this defines the format the final string will take:

MessageBox.Show("Division test with formatting.. " & _ String.Format("{0:n3}", dblNumber), "Floating Points")

You passed String.Format two parameters. The first parameter, "{0:n3}", is the format that you want. The second parameter, dblNumber, is the value that you want to format. Note that since you are formatting a number to a string representation, you do not need to provide the ToString method after dblNumber as in the previous call to the Show method of the MessageBox class. This is because the String.Format method is looking for a number and not a string.

The 0 in the format tells String.Format to work with the zeroth data parameter, which is just a cute way of saying “the second parameter”, or dblNumber. What follows the colon is how you want dblNumber to be formatted. You said n3, which means “floating-point number, three decimal places.” You could have said n2 for “floating-point number, two decimal places.”

Localized Formatting

When building .NET applications, it’s important to realize that the user may be familiar with cultural conventions that are uncommon to you. For example, if you live in the United States, you’re used to seeing the decimal separator as a period (.). However, if you live in France, the decimal separator is actually a comma (,).

Windows can deal with such problems for you based on the locale settings of the computer. If you use the .NET Framework in the correct way, by and large you’ll never need to worry about this problem.

Here’s an example—if you use a formatting string of n3 again, you are telling .NET that you want to format the number with thousands separators and also that you want the number displayed to three decimal places (1,714.286).

The equation changed from 12 / 7 to 12000 / 7 to allow the display of the thousands separator (,).

Now, if you tell your computer that you want to use the French locale settings, and you run the same code (you make no changes whatsoever to the application itself), you’ll see 1 714,286.

You can change your language options by going to the Control Panel and clicking the Regional and Language Options icon and changing the language to French.

In France, the thousands separator is a space, not a comma, while the decimal separator is a comma, not a period. By using String.Format appropriately, you can write one application that works properly regardless of how the user has configured the locale settings on the computer.

Replacing Substrings

Another common string manipulation replaces occurrences of one string with another. To demonstrate this, in the next Try It Out you’ll modify your Strings application to replace the string "Hello" with the string "Goodbye".

  1. Open the Strings project that you were working with earlier.

  2. Return to the Forms Designer for Form1, add another Button control and set its Name property to btnReplace and set its Text property to Replace. Double-click the button and add the following highlighted code to its Click event handler:

    Private Sub btnReplace_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnReplace.Click 'Declare variables Dim strData As String Dim strResults As String 'Get the text from the TextBox strData = txtString.Text 'Replace the string occurance strResults = strData.Replace("Hello", "Goodbye") 'Display the new string MessageBox.Show(strResults, "Strings") End Sub

  3. Run the project and enter Hello World! into the text box (using this exact capitalization).

  4. Click the Replace button. You should see a message box that says Goodbye World!

Tip

Replace works by taking the substring to look for as the first parameter and the new substring to replace it with as the second parameter. After the replacement is made, a new string is returned that you can display in the usual way.

'Replace the string occurance strResults = strData.Replace("Hello", "Goodbye")

You’re not limited to a single search and replace within this code. If you enter Hello twice into the text box and click the button, you’ll notice two Goodbye returns. However, the case is important—if you enter hello, it will not be replaced. You’ll take a look at case-insensitive string comparisons in the next chapter.

Using Dates

Another data type that you’ll often use is Date. This data type holds, not surprisingly, a date value. You learn to display the current date in the next Try It Out.

  1. Create a new Windows Forms Application project called Date Demo.

  2. In the usual way, use the Toolbox to draw a new Button control on the form. Call it btnShowDate and set its Text property to Show Date.

  3. Double-click the button to bring up its Click event handler and add this code:

    Private Sub btnShowDate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnShowDate.Click'Declare variable Dim dteResults As Date 'Get the current date and time dteResults = Now 'Display the results MessageBox.Show(dteResults.ToString, "Date Demo") End Sub

  4. Save your project by clicking the Save All button on the toolbar.

  5. Run the project and click the button. You should see something like Figure 3–11 depending on the locale settings on your machine.

Date Demo

Figure 3–11

Tip

The Date data type can be used to hold a value that represents any date and time. After creating the variable, you initialized it to the current date and time using the Now property. Then you display the date in a message box dialog box. Note that since you want to display a Date data type as a string, that you once again use the ToString method to convert the results to a string format.

'Declare variable Dim dteResults As Date 'Get the current date and time dteResults = Now 'Display the results MessageBox.Show(dteResults.ToString, "Date Demo")

Date data types aren’t any different from other data types, although you can do more with them. In the next couple of sections, you’ll see ways to manipulate dates and control the way they are displayed on the screen.

Formatting Date Strings

You’ve already seen one way in which dates can be formatted. By default, if you pass a Date variable to MessageBox.Show, the date and time are displayed as shown in Figure 3–11.

Because this machine is in the United States, the date is shown in m/d/yyyy format and the time is shown using the 12-hour clock. This is another example of how the computer’s locale setting affects the formatting of different data types. For example, if you set your computer to the United Kingdom locale, the date is in dd/mm/yyyy format and the time is displayed using the 24-hour clock, for example, 07/08/2004 07:02:47.

Although you can control the date format to the nth degree, it’s best to rely on .NET to ascertain how the user wants strings to look and automatically display them in their preferred format. In the next Try It Out, you’ll look at four useful methods that enable you to format dates.

  1. Return to the Code Editor for Form1, find the Click event handler for the button, and add the following highlighted code:

    'Display the results MessageBox.Show(dteResults.ToString, "Date Demo")

            'Display dates
            MessageBox.Show(dteResults.ToLongDateString, "Date Demo")
            MessageBox.Show(dteResults.ToShortDateString, "Date Demo")
    
            'Display times
            MessageBox.Show(dteResults.ToLongTimeString, "Date Demo")
            MessageBox.Show(dteResults.ToShortTimeString, "Date Demo")
    

    End Sub

  2. Run the project. You’ll be able to click through five message boxes. You have already seen the first message box dialog box; it displays the date and time according to your computers locale settings. The next message dialog box displays the long date, and the next message dialog box displays the short date. The fourth message box displays the long time, and the last message box displays the short time.

Tip

You’re seeing the four basic ways that you can display dates and times in Windows applications, namely long date, short date, long time, and short time. The names of the formats are self-explanatory!

'Display dates MessageBox.Show(dteResults.ToLongDateString, "Date Demo") MessageBox.Show(dteResults.ToShortDateString, "Date Demo") 'Display times MessageBox.Show(dteResults.ToLongTimeString, "Date Demo") MessageBox.Show(dteResults.ToShortTimeString, "Date Demo")

Extracting Date Properties

When you have a variable of type Date, there are several properties that you can call to learn more about the date; let’s look at them.

  1. Return to the Forms Designer for the Date Demo project and add another Button control to Form1 and set its Name property to btnDateProperties and its Text property to Date Properties. Double-click the button and add the following highlighted code to the Click event:

    Private Sub btnDateProperties_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDateProperties.Click

            'Declare variable
            Dim dteResults As Date
    
            'Get the current date and time
            dteResults = Now
    
            'Display the various date properties
            MessageBox.Show("Month: " & dteResults.Month, "Date Demo")
            MessageBox.Show("Day: " & dteResults.Day, "Date Demo")
            MessageBox.Show("Year: " & dteResults.Year, "Date Demo")
            MessageBox.Show("Hour: " & dteResults.Hour, "Date Demo")
            MessageBox.Show("Minute: " & dteResults.Minute, "Date Demo")
            MessageBox.Show("Second: " & dteResults.Second, "Date Demo")
            MessageBox.Show("Day of week: " & dteResults.DayOfWeek, "Date Demo")
            MessageBox.Show("Day of year: " & dteResults.DayOfYear, "Date Demo")
    

    End Sub

  2. Run the project. If you click the button, you’ll see a set of fairly self-explanatory message boxes.

Tip

Again, there’s nothing here that’s rocket science. If you want to know the hour, use the Hour property. To get at the year, use Year, and so on.

Date Constants

In the preceding Try It Out, when you called DayOfWeek property, you were actually given an integer value, as shown in Figure 3–12.

Date Demo

Figure 3–12

The date that we’re working with, September 3, 2007, is a Monday, and, although it may not be immediately obvious, Monday is 1. Because the first day of the week is Sunday in the United States, you start counting from Sunday, with Sunday being 0. However, there is a possibility that you’re working on a computer whose locale setting starts the calendar on a Monday, in which case DayOfWeek would return 0. Complicated? Perhaps, but just remember that you can’t guarantee that what you think is "Day 1" is always going to be Monday. Likewise, what’s Wednesday in English is Mittwoch in German.

If you need to know the name of the day or the month in your application, a better approach is to get .NET to get the name for you, again from the particular locale settings of the computer, as you do in the next Try It Out.

  1. Return to the Form Designer in the Date Demo project, add a new Button control and set its Name property to btnDateNames and its Text property to Date Names. Double-click the button and add the following highlighted code to the Click event handler:

    Private Sub btnDateNames_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDateNames.Click

          'Declare variable
            Dim dteResults As Date
    
            'Get the current date and time
            dteResults = Now
    
            MessageBox.Show("Weekday name: " & dteResults.ToString("dddd"), _
                "Date Demo")
            MessageBox.Show("Month name: " & dteResults.ToString("MMMM"), _
                "Date Demo")
    

    End Sub

  2. Run the project and click the button. You will see a message box that tells you the weekday name (Monday, for example) and a second one that tells you the month (September, for example).

Tip

When you used your ToLongDateString method and its siblings, you were basically allowing .NET to look in the locale settings for the computer for the date format the user preferred. In this example, you’re using the ToString method but supplying your own format string.

MessageBox.Show("Weekday name: " & dteResults.ToString("dddd"), _ "Date Demo") MessageBox.Show("Month name: " & dteResults.ToString("MMMM"), _ "Date Demo")

Usually, it’s best practice not to use the ToString method to format dates to different string values, because you should rely on the built-in formats in .NET, but here you’re using the "dddd" string to get the weekday name and "MMMM" to get the month name. (The case is important here—”mmmm" won’t work.)

To show this works, if the computer is set to use Italian locale settings, you get one message box telling you the weekday name is Luned~I and another telling you the month name is Settembre.

Defining Date Literals

You know that if you want to use a string literal in your code, you can do this:

Dim strResults As StringstrResults = "Woobie"

Date literals work in more or less the same way. However, you use pound signs (#) to delimit the start and end of the date. You learn to define date literals in the next Try It Out.

  1. Return to the Forms Designer for the Date Demo project and add another Button control to the form and set its Name property to btnDateLiterals and its Text property to Date Literals. Double-click the button and add the following highlighted code to the Click event handler:

    Private Sub btnDateLiterals_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDateLiterals.Click

            'Declare variable
            Dim dteResults As Date
    
            'Set a date and time
            dteResults = #1/1/2010 8:01:00 AM#
    
            'Display the date and time
            MessageBox.Show(dteResults.ToLongDateString & " " & _
                dteResults.ToLongTimeString, "Date Demo")
    

    End Sub

  2. Run the project and click the button. You should see the message box shown in Figure 3–13.

Date Demo

Figure 3–13

Tip

When defining a date literal, it must be defined in the mm/dd/yyyy format, regardless of the actual locale settings of the computer. You may or may not see an error if you try to define the date in the format dd/mm/yyyy. This is because you could put in a date in the format dd/mm/yyyy (for example, 06/07/2008) that is also a valid date in the required mm/dd/yyyy format. This requirement reduces ambiguity: Does 6/7/2008 mean July 6 or June 7?

In fact, this is a general truth of programming as a whole: There are no such things as dialects when writing software. It’s usually best to conform to North American standards. As you’ll see through the rest of this book, this includes variables and method names, for example GetColor rather than GetColour.

It’s also worth noting that you don’t have to supply both a date and a time. You can supply one, the other, or both.

Manipulating Dates

One thing that’s always been pretty tricky for programmers to do is manipulate dates. Most of you will remember New Year’s Eve 1999, waiting to see whether computers could deal with tipping into a new century. Also, dealing with leap years has always been a bit of a problem.

The next turn of the century that also features a leap year will be 2399 to 2400. In the next Try It Out, you’ll take a look at how you can use some of the methods available on the Date data type to adjust the date around that particular leap year.

  1. Return to the Forms Designer for the Date Demo project and add another Button control to the form and set its Name property to btnDateManipulation and its Text property to Date Manipulation. Double-click the button and add the following highlighted code to the Click event handler:

    Private Sub btnDateManipulation_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDateManipulation.Click

            'Declare variables
            Dim dteStartDate As Date
            Dim dteChangedDate As Date
    
            'Start in the year 2400
            dteStartDate = #2/28/2400#
    
            'Add a day and display the results
            dteChangedDate = dteStartDate.AddDays(1)
            MessageBox.Show(dteChangedDate.ToLongDateString, "Date Demo")
    
            'Add some months and display the results
            dteChangedDate = dteStartDate.AddMonths(6)
            MessageBox.Show(dteChangedDate.ToLongDateString, "Date Demo")
    
            'Subtract a year and display the results
            dteChangedDate = dteStartDate.AddYears(-1)
            MessageBox.Show(dteChangedDate.ToLongDateString, "Date Demo")
    

    End Sub

  2. Run the project and click the button. You’ll see three message boxes, one after another. The first message box displays the long date for 2/29/2400, whereas the second message box displays the long date for 8/28/2400. The final message box displays the long date for 2/28/2399.

Tip

The Date data type supports several methods for manipulating dates. Here are three of them:

'Add a day and display the results dteChangedDate = dteStartDate.AddDays(1) MessageBox.Show(dteChangedDate.ToLongDateString, "Date Demo") 'Add some months and display the results dteChangedDate = dteStartDate.AddMonths(6) MessageBox.Show(dteChangedDate.ToLongDateString, "Date Demo") 'Subtract a year and display the results dteChangedDate = dteStartDate.AddYears(-1) MessageBox.Show(dteChangedDate.ToLongDateString, "Date Demo")

It’s worth noting that when you supply a negative number to any of the Add methods when working with Date variables, the effect is subtraction (demonstrated by going from 2400 back to 2399). The other important Add methods are AddHours, AddMinutes, AddSeconds, and AddMilliseconds.

Boolean

So far, you’ve seen the Integer, Double, Single, String, and Date data types. The other one you need to look at is Boolean. After you’ve done that, you’ve seen all of the simple data types that you’re most likely to use in your programs.

A Boolean variable can be either True or False. It can never be anything else. Boolean values are really important when it’s time for your programs to start making decisions, which is something you look at in more detail in Chapter 4.

Storing Variables

The most limited resource on your computer is typically its memory. It is important that you try to get the most out of the available memory. Whenever you create a variable, you are using a piece of memory, so you must strive to use as few variables as possible and use the variables that you do have in the most efficient manner.

Today, absolute optimization of variables is not something you need to go into a deep level of detail about, for two reasons. First, computers have far more memory these days, so the days when programmers tried to cram payroll systems into 32KB of memory are long gone. Second, the compilers themselves have a great deal of intelligence built into them these days, to help generate the most optimized code possible.

Binary

Computers use binary to represent everything. That means that whatever you store in a computer must be expressed as a binary pattern of ones and zeros. Take a simple integer, 27. In binary code, this number is actually 11011, each digit referring to a power of two. The diagram in Figure 3–14 shows how you represent 27 in the more familiar base-10 format, and then in binary.

base-10 diagram

Figure 3–14

Although this may appear to be a bit obscure, look what’s happening. In base-10, the decimal system that you’re familiar with, each digit fits into a slot. This slot represents a power of 10—the first representing 10 to the power zero, the second 10 to the power one, and so on. If you want to know what number the pattern represents, you take each slot in turn, multiply it by the value it represents, and add the results.

The same applies to binary—it’s just that you’re not familiar with dealing with base-2. To convert the number back to base-10, you take the digit in each slot in turn and multiply that power of two by the number that the slot represents (zero or one). Add all of the results together and you get the number.

Bits and Bytes

In computer terms, a binary slot is called a bit. It is the smallest possible unit of information, the answer to a single yes/no question, represented by a part of the computer’s circuitry that either has electricity flowing in it or not. The reason why there are eight slots/bits on the diagram in Figure 3–14 is that there are eight bits in a byte. A byte is the unit of measurement that you use when talking about computer memory.

A kilobyte or KB is 1,024 bytes. You use 1,024 rather than 1,000 because 1,024 is the 10th power of 2, so as far as the computer is concerned it’s a round number. Computers don’t tend to think of things in terms of 10s like you do, so 1,024 is more natural to a computer than 1,000 is.

Likewise, a megabyte is 1,024 kilobytes, or 1,048,576 bytes. Again, that is another round number because this is the 20th power of 2. A gigabyte is 1,024 megabytes, or 1,073,741,824 bytes. (Again, think 2 to the power of 30 and you’re on the right track.) Finally, a terabyte is 2 to the 40th power, and a petabyte is 2 to the 50th power.

So what’s the point of all this? Well, having an understanding of how computers store variables helps you design your programs better. Suppose your computer has 256MB of memory. That’s 262,144KB or 268,435,456 bytes or (multiply by 8) 2,147,483,648 bits. As you write your software, you have to make the best possible use of this available memory.

Representing Values

Most desktop computers in use today are 32-bit, which means that they’re optimized for dealing with integer values that are 32 bits in length. The number you just saw in the example was an 8-bit number. With an 8-bit number, the largest value you can store is:

1x128 + 1x64 + 1x32 + 1x16 + 1x8 + 1x4 + 1x2 + 1x1 = 255

A 32-bit number can represent any value between –2,147,483,648 and 2,147,483,647. Now, if you define a variable like this:

Dim intNumber As Integer

you want to store an integer. In response to this, .NET will allocate a 32-bit block of memory in which you can store any number between 0 and 2,147,483,647. Also, remember you have only a finite amount of memory, and on your 256MB computer; you can store only a maximum of 67,108,864 long numbers. Sounds like a lot, but remember that memory is for sharing. You shouldn’t write software that deliberately tries to use as much memory as possible. Be frugal!

You also defined variables that were double-precision floating-point numbers, like this:

Dim dblNumber As Double

To represent a double-precision floating point number, you need 64 bits of memory. That means you can store only a maximum of 33,554,432 double-precision floating-point numbers.

Single-precision floating-point numbers take up 32 bits of memory—in other words half as much as a double-precision number and the same as an integer value.

If you do define an integer, whether you store 1, 3, 249, or 2,147,483,647, you’re always using exactly the same amount of memory, 32 bits. The size of the number has no bearing on the amount of memory required to store it. This might seem incredibly wasteful, but the computer relies on numbers of the same type taking the same amount of storage. Without this, it would be unable to work at a decent speed.

Now look at how you define a string:Dim strResults As StringstrResults = "Hello World!"

Unlike integers and doubles, strings do not have a fixed length. Each character in the string takes up two bytes, or 16 bits. So, to represent this 12-character string, you need 24 bytes, or 192 bits. That means that your computer is able to store only a little over two million strings of that length. Obviously, if the string is twice as long, you can hold half as many, and so on.

A common mistake that new programmers make is not taking into consideration the impact the data type has on storage. If you have a variable that’s supposed to hold a string, and you try to hold a numeric value in it, like this:Dim strData As StringstrData = "65536"you’re using 10 bytes (or 80 bits) to store it. That’s less efficient than storing the value in an Integer data type. To store this numerical value in a string, each character in the string has to be converted into a numerical representation. This is done according to something called Unicode, which is a standard way of defining the way computers store characters. Each character has a unique number between 0 and 65,535, and it’s this value that is stored in each byte allocated to the string.

Here are the Unicode codes for each character in the string:

  • 6: Unicode 54, binary 0000000000110110

  • 5: Unicode 53, binary 0000000000110101

  • 5: Unicode 53, binary 0000000000110101

  • 3: Unicode 51, binary 0000000000110011

  • 6: Unicode 54, binary 0000000000110110

Each character requires 16 bits, so to store a 5-digit number in a string requires 80 bits—five 16 bit numbers. What you should do is this:

Dim intNumber As IntegerintNumber = 65536

This stores the value as a single number binary pattern. An Integer uses 32 bits, so the binary representation will be 00000000000000010000000000000000, far smaller than the space needed to store it as a string.

Converting Values

Although strings seem natural to us, they’re unnatural to a computer. A computer wants to take two numbers and perform some simple mathematical operation on them. However, a computer can perform such a vast number of these simple operations each second that you, as humans, get the results you want.

Let’s imagine that a computer wants to add 1 to the value 27. You already know that you can represent 27 in binary as 11011. Figure 3–15 shows what happens when you want to add 1 to the value 27.

As you can see, binary math is no different from decimal (base-10) math. If you try to add one to the first bit, it won’t fit, so you revert it to zero and carry the one to the next bit. The same happens, and you carry the one to the third bit. At this point, you’ve finished, and if you add up the value you get 28, as intended.

base2 diagram

Figure 3–15

Any value that you have in your program ultimately has to be converted to simple numbers for the computer to do anything with them. To make the program run more efficiently, you have to keep the number of conversions to a minimum. Here’s an example:

Dim strResults As StringstrResults = "27"strResults = strResults + 1MessageBox.Show(strResults)

Let’s look at what’s happening:

  1. You create a string variable called strResults.

  2. You assign the value 27 to that string. This uses 4 bytes of memory.

  3. To add 1 to the value, the computer has to convert 27 to an internal, hidden Integer variable that contains the value 27. This uses an additional 4 bytes of memory, taking the total to 8. However, more importantly, this conversion takes time!

  4. When the string is converted to an integer, 1 is added to it.

  5. The new value then has to be converted into a string.

  6. The string containing the new value is displayed on the screen.

To write an efficient program, you don’t want to be constantly converting variables between different types. You want to perform the conversion only when it’s absolutely necessary.

Here’s some more code that has the same effect:

Dim intNumber As IntegerintNumber = 27intNumber += 1MessageBox.Show(intNumber.ToString)

  1. You create an integer variable called intNumber.

  2. You assign the value 27 to the variable.

  3. You add 1 to the variable.

  4. You convert the variable to a string and display it on the screen.

In this case, you have to do only one conversion, and it’s a logical one; use the ToString method on the Integer data type. MessageBox.Show works in terms of strings and characters, so that’s what it’s most comfortable with.

What you have done is cut the conversions from two (string to integer, integer to string) down to one. This will make your program run more efficiently and use less memory. Again, it’s a small improvement, but imagine this improvement occurring hundreds of thousands of times each minute—you’ll get an improvement in the performance of the system as a whole.

It is absolutely vital that you work with the correct data type for your needs. In simple applications like the ones you’ve created in this chapter, a performance penalty is not really noticeable. However, when you write more complex, sophisticated applications, you’ll really want to optimize your code by using the right data type.

Methods

A method is a self-contained block of code that does something. Methods, also called procedures, are essential for two reasons. First, they break a program up and make it more understandable. Second, they promote code reuse—a topic you’ll be spending most of your time on throughout the rest of this book.

As you know, when you write code you start with a high-level algorithm and keep refining the detail of that algorithm until you get the software code that expresses all of the algorithms up to and including the high-level one. A method describes a line in one of those algorithms, for example “open a file”, “display text on screen”, “print a document”, and so on.

Knowing how to break up a program into methods is something that comes with experience. To add to the frustration, it’s far easier to understand why you need to use methods when you’re working on far more complex programs than the ones you’ve seen so far. In the rest of this section, we’ll endeavor to show you how and why to use methods.

Why Use Methods?

In day-to-day use, you need to pass information to a method for it to produce the expected results. This might be a single integer value, a set of string values, or a combination of both. These are known as input values. However, some methods don’t take input values, so having input values is not a requirement of a method. The method uses these input values and a combination of environmental information (for instance, facts about the current state of the program that the method knows about) to do something useful.

We say that when you give information to a method, you pass it data. You can also refer to that data as parameters. Finally, when you want to use a method, you call it.

To summarize, you call a method, passing data in through parameters.

The reason for using methods is to promote this idea of code reuse. The principle behind using a method makes sense if you consider the program from a fairly high level. If you have an understanding of all the algorithms involved in a program, you can find commonality. If you need to do the same thing more than once, you should wrap it up into a method that you can reuse.

Imagine you have a program that comprises many algorithms. Some of those algorithms call for the area of a circle to be calculated. Because some of those algorithms need to know how to calculate the area of a circle, it’s a good candidate for a method. You write code that knows how to find the area of a circle given its radius, encapsulate it (wrap it up) into a method, which you can reuse when you’re coding the other algorithms. This means that you don’t have to keep writing code that does the same thing—you do it once and reuse it as often as needed.

It might be the case that one algorithm needs to work out the area of a circle with 100 for its radius, and another needs to work out one with a radius of 200. By building the method in such a way that it takes the radius as a parameter, you can use the method from wherever you want.

With Visual Basic 2008, you can define a method using the Sub keyword or using the Function keyword. Sub, short for subroutine, is used when the method doesn’t return a value, as mentioned in Chapter 1. Function is used when the method returns a value.

Methods You’ve Already Seen

The good news is that you’ve been using methods already. Consider the following code that you wrote at the beginning of this chapter:

Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click 'Define a variable for intNumber Dim intNumber As Integer 'Set the initial value intNumber = 27 'Add 1 to the value of intNumber intNumber = intNumber + 1 'Display the new value of intNumber MessageBox.Show("Value of intNumber + 1 = " & intNumber.ToString, _ "Variables") End Sub

That code is a method—it’s a self-contained block of code that does something. In this case, it adds 1 to the value of intNumber and displays the result in a message box.

This method does not return a value (that is, it’s a subroutine, so it starts with the Sub keyword and ends with the End Sub statement). Anything between these two statements is the code assigned to the method. Let’s take a look at how the method is defined (this code was automatically created by Visual Basic 2008):

Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click

  1. First of all, you have the word Private. The meaning of this keyword is discussed in later chapters. For now, think of it as ensuring that this method cannot be called up by anything other than the user clicking the Add button.

  2. Second, you have the keyword Sub to tell Visual Basic 2008 that you want to define a subroutine.

  3. Third, you have btnAdd_Click. This is the name of the subroutine.

  4. Fourth, you have ByVal sender As System.Object, ByVal e As System.EventArgs. This tells Visual Basic 2008 that the method takes two parameters—sender and e. We’ll talk about this more later.

  5. Finally, you have Handles btnAdd.Click. This tells Visual Basic 2008 that this method should be called whenever the Click event on the control btnAdd is fired.

In the next Try It Out, you take a look at how you can build a method that displays a message box and call the same method from three separate buttons.

  1. Create a new Windows Forms Application project called Three Buttons.

  2. Use the Toolbox to draw three buttons on the form.

  3. Double-click the first button (Button1) to create a new Click event handler. Add the highlighted code:

    Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'Call your method SayHello() End Sub Private Sub SayHello() 'Display a message box MessageBox.Show("Hello World!", "Three Buttons") End Sub

  4. Save your project by clicking the Save All button on the toolbar.

  5. Run the project and you’ll see the form with three buttons appear. Click the topmost button and you’ll see “Hello World!” displayed in a message box.

Tip

As you know now, when you double-click a Button control in the Designer, a new method is automatically created:

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click End Sub

The Handles Button1.Click statement at the end tells Visual Basic 2008 that this method should automatically be called when the Click event on the button is fired. As part of this, Visual Basic 2008 provides two parameters, which you don’t have to worry about for now. Outside of this method, you’ve defined a new method:

Private Sub SayHello() 'Display a message box MessageBox.Show("Hello World!", "Three Buttons") End Sub

The new method is called SayHello. Anything that appears between the Sub and End Sub keywords is part of the method and when that method is called, the code is executed. In this case, you’ve asked it to display a message box.

So you know that when the button is clicked, Visual Basic 2008 will call the Button1_Click method. You then call the SayHello method. The upshot of all this is that when the button is clicked, the message box is displayed:

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'Call your method SayHello() End Sub

That should make the general premise behind methods a little clearer, but why did you need to break the code into a separate method to display the message box? You learn more about that in the next Try It Out.

  1. If your project is still running, stop it.

  2. Return to the Forms Designer, and double-click the second button and add the highlighted code to the new event handler:

    Private Sub Button2_Click(ByVal sender As System.Object, _ BCyVal e As System.EventArgs) Handles Button2.Click 'Call your method SayHello() End Sub

  3. Switch back to the Forms Designer and double-click the third button and add the highlighted code:

    Private Sub Button3_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button3.Click 'Call your method SayHello() End Sub

  4. Now run the project. You’ll notice that when you click each of the buttons, they all bring up the same message box.

  5. Stop the project and find the SayHello method definition. Change the text to be displayed, like this:

    Private Sub SayHello() 'Display a message box MessageBox.Show("I have changed!", "Three Buttons") End Sub

  6. Run the project again and click each of the three buttons. You’ll notice that the text displayed on the message boxes has changed.

Tip

Each of the event handlers calls the same SayHello() method:

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'Call your method SayHello() End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click 'Call your method SayHello() End Sub Private Sub Button3_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button3.Click 'Call your method SayHello() End Sub

You’ll also notice that the Handles keyword on each of the methods ties the method to a different control—Button1, Button2, or Button3.

What’s really important (and clever) here is that when you change the way that SayHello works, the effect you see on each button is the same. This is a really important programming concept. You can centralize code in your application so that when you change it in once place, the effect is felt throughout the application. Likewise, this saves you from having to enter the same or very similar code repeatedly.

Building a Method

In the next Try It Out, you’ll build a method that’s capable of returning a value. Specifically, you’ll build a method that can return the area of a circle if its radius is given. You can do this with the following algorithm:

  1. Square the radius.

  2. Multiply it by pi.

  1. To try out this exercise, reuse the Three Buttons project and return to the Code Editor.

  2. Add this code to define a new method (which will be a function, because it returns a value):

    'CalculateAreaFromRadius—find the area of a circle Private Function CalculateAreaFromRadius(ByVal radius As Double) As Double 'Declare variables Dim dblRadiusSquared As Double Dim dblResult As Double 'Square the radius dblRadiusSquared = radius * radius 'Multiply it by pi dblResult = dblRadiusSquared * Math.PI 'Return the result Return dblResult End Function

  3. Now delete the existing code from the Button1_Click event handler, and add the highlighted code:

    Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'Declare variable Dim dblArea As Double 'Calculate the area of a circle with a radius of 100 dblArea = CalculateAreaFromRadius(100) 'Display the results MessageBox.Show(dblArea.ToString, "Area of 100") End Sub

  4. Run the project and click Button1. You’ll see results like the one shown in Figure 3–16:

Area of 100

Figure 3–16

Tip

First, you build a separate method called CalculateAreaFromRadius. You do this by using the Private Function . . . End Function block.

Private Function CalculateAreaFromRadius(ByVal radius As Double) As Double .. End Function

Anything between Private Function and End Function is the body of the method and will be executed only when the method is called.

The ByVal radius As Double portion defines a parameter for the method. When a parameter is passed by value, as indicated here by the keyword ByVal, .NET in effect creates a new variable and stores the passed parameter information in it. Even if the method is called with a variable given for the parameter, the contents of that original variable are not modified by the method. In this case, you’re telling .NET that you want to pass a parameter into the method called radius. In effect, this statement creates a variable called radius, just as if you had done this:

Dim radius As Double

In fact, there’s a little more. The variable will be automatically set to the value passed through as a parameter, so if you pass 200 through as the value of the parameter, what you’re effectively doing is this:

Dim radius As Double = 200

If you passed 999 as the value of the parameter, you’d have this:

Dim radius As Double = 999

Another way of passing a parameter is by reference, using the keyword ByRef instead of ByVal. When a parameter is passed by reference, the parameter name used within the method body effectively becomes another name for the variable specified when the method is called, so that anything the method does that modifies the parameter value modifies the original variable value as well.

The As Double sitting at the end of the method declaration tells Visual Basic 2008 that this method will return a double-precision floating-point number back to whoever called it:

Private Function CalculateAreaFromRadius(ByVal radius As Double) As Double

Now you can look at the method properly. First off, you know that to find the area of a circle you have this algorithm:

  1. Get a number that represents the radius of a circle.

  2. Square the number.

  3. Multiply it by pi (p).

And that’s precisely what you’ve done:

'Declare variables Dim dblRadiusSquared As Double Dim dblResult As Double 'Square the radius dblRadiusSquared = radius * radius 'Multiply it by pi dblResult = dblRadiusSquared * Math.PI

The Math.PI in the previous code is a constant defined in .NET that defines the value of pi (p) for us. After the last line, you need to return the result to whatever code called the method. This is done with this statement:

'Return the result Return dblResult

The code you added in Button1_Click calls the method and tells the user the results:

'Declare variable Dim dblArea As Double 'Calculate the area of a circle with a radius of 100 dblArea = CalculateAreaFromRadius(100) 'Display the results MessageBox.Show(dblArea.ToString, "Area of 100")

The first thing to do is define a variable called dblArea that will contain the area of the circle. You set this variable to whatever value CalculateAreaFromRadius returns. Using parentheses at the end of a method name is how you send the parameters. In this case, you’re passing just one parameter and you’re passing the value 100.

After you call the method, you wait for the method to finish calculating the area. This area is returned from the method (the Return result line defined within CalculateAreaFromRadius) and stored in the variable dblArea. You can then display this on the screen in the usual way.

Choosing Method Names

The .NET Framework has a few standards for how things should be named. These conventions help developers move between languages—a topic discussed in Chapter 2. We recommend that whenever you create a method, you use Pascal casing. This is a practice in which the first letter in each word in the method is uppercase but nothing else is. This is merely a suggestion for best coding practices and is not a requirement of Visual Basic 2008. An example of this is as follows:

  • CalculateAreaFromRadius

  • OpenXmlFile

  • GetEnvironmentValue

Note that even when an abbreviation is used (in this case, XML), it isn’t written in uppercase. This alleviates confusion for developers, who may or may not know how something should be capitalized.

We recommend that you always write parameter names in camel casing. (If you’ve ever seen Java code, you’ll be familiar with this.) To get camel casing, you do the same as Pascal casing, but you don’t capitalize the very first letter:

  • myAccount

  • customerDetails

  • updatedDnsRecord

Again, abbreviations (such as DNS) are not treated as a special case, so they appear as a mix of upper and lowercase letters, just like in Pascal casing.

The name camel casing comes from the fact that the identifier has a hump in the middle, for example, camelCasing. Pascal casing comes from the fact that the convention was invented for use with the programming language Pascal.

In Chapter 2, you saw that .NET isn’t tied to a particular language. Because some languages are casesensitive and others are not, it’s important that you define standards to make life easier for programmers who may be coming from different programming language backgrounds.

The term case-sensitive means that the positions of uppercase and lowercase letters are important. In a case-sensitive language, MYACCOUNT is not the same as myAccount. However, Visual Basic 2008 is not a case-sensitive language, meaning that for all intents and purposes you can do whatever you like with respect to capitalization; in other words MYACCOUNT would be the same as mYacCounT.

Note that languages such as Java, C#, and C++ are case-sensitive.

Scope

When introducing the concept of methods, we described them as self-contained. This has an important effect on the way that variables are used and defined in methods. Imagine you have these two methods, both of which define a variable called strName:

Private Sub DisplaySebastiansName() 'Declare variable and set value Dim strName As String strName = "Sebastian Blackwood" 'Display results MessageBox.Show(strName, "Scope Demo") End Sub Private Sub DisplayBalthazarsName() 'Declare variable and set value Dim strName As String strName = "Balthazar Keech" 'Display results MessageBox.Show(strName, "Scope Demo") End Sub

Even though both of these methods use a variable with the same name (strName), the self-contained feature of methods means that this is perfectly practicable and the variable names won’t affect each other. Try it out next.

  1. Create a new Windows Forms Application project called Scope Demo.

  2. Add a Button control to the form and set its Name property btnScope and its Text property to Scope. Double-click the button and add the following highlighted code to the Click event handler and add the other two methods:

    Private Sub btnScope_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnScope.Click 'Call a method DisplayBalthazarsName() End Sub Private Sub DisplaySebastiansName() 'Declare variable and set value Dim strName As String strName = "Sebastian Blackwood" 'Display results MessageBox.Show(strName, "Scope Demo") End Sub Private Sub DisplayBalthazarsName() 'Declare variable and set value Dim strName As String strName = "Balthazar Keech" 'Display results MessageBox.Show(strName, "Scope Demo") End Sub

  3. Save your project by clicking the Save All button on the toolbar.

  4. Run the project and you’ll see the message box displaying the name Balthazar Keech when you click the button.

Tip

What this exercise illustrates is that even though you’ve used the same variable name in two separate places, the program still works as intended:

Private Sub DisplaySebastiansName() 'Declare variable and set value Dim strName As String strName = "Sebastian Blackwood" 'Display results MessageBox.Show(strName, "Scope Demo") End Sub Private Sub DisplayBalthazarsName() 'Declare variable and set value Dim strName As String strName = "Balthazar Keech" 'Display results MessageBox.Show(strName, "Scope Demo") End Sub

When a method starts running, the variables that are defined within that method (in other words, between Sub and End Sub, or between Function and End Function) are given local scope. The scope defines which parts of the program can see the variable, and local specifically means within the current method.

The strName variable technically doesn’t exist until the method starts running. At this point, .NET and Windows allocate memory to the variable so that it can be used in the code. First, you set the value and then you display the message box. Therefore, in this case as you’re calling the method DisplayBalthazarsName, the variable is created the moment the method is called, you run the code in the method that alters the newly created version of strName, and when the method has finished, the variable is deleted.

You will see in Chapter 4 that scope can even be limited to loops within your subroutines and functions.

Summary

This chapter introduced the concept of writing software not just for Visual Basic 2008 but also for all programming languages. We started by introducing the concept of an algorithm—the underpinnings of all computer software. We then introduced the concept of variables, and looked closely at the most commonly used data types: Integer, Double, String, Date, and Boolean. You saw how you could use these data types to perform operations such as mathematical operations, concatenating strings, returning the length of a string, splitting text into substrings, retrieving the current date, and extracting date properties. You then looked at how variables are stored in the computer.

After this, you looked at methods—what they are, why you need them, how to create them, and how the variables you declare within your methods have local scope within that method and do not apply outside of it. We also described the difference between a function and a subroutine.

To summarize, you should know:

  • What an algorithm is and how it applies to software development

  • How to declare and use the most common types of variables

  • How to use the most common string functions when working with the String data type

  • How to use the Date data type and display dates and times so that they are automatically localized to the user’s computer settings

  • How to create and use simple methods

Exercises

  1. Create a Windows application with two button controls. In the Click event for the first button, declare two Integer variables and set their values to any number that you like. Perform any math operation on these variables and display the results in a message box. In the Click event for the second button, declare two String variables and set their values to anything that you like. Perform a string concatenation on these variables and display the results in a message box.

  2. Create a Windows application with a text box and a button control. In the button’s Click event, display three message boxes. The first message box should display the length of the string that was entered into the text box. The second message box should display the first half of the string, and the third message box should display the last half of the string.

Beginning Microsoft® Visual Basic® 2008, Copyright © 2008 by Wiley Publishing, Inc., ISBN: 978-0-470-19134-7, Published by Wiley Publishing, Inc., All Rights Reserved. Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates.