BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Programming Visual Basic .NET
Programming Visual Basic .NET, Second Edition By Jesse Liberty
April 2003
Pages: 558

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Visual Basic .NET andthe .NET Framework
Programming Visual Basic .NET is a comprehensive guide to the .NET version of the Visual Basic language and its use as a tool for programming on Microsoft's .NET platform. One learns VB.NET specifically to create .NET applications; pretending otherwise would miss the point of the language. Thus, this book does not consider VB.NET in a vacuum but places the language firmly in the context of Microsoft's .NET platform and in the development of desktop and Internet applications.
This chapter introduces both the Visual Basic .NET language and the .NET platform, including the .NET Framework.
Once upon a time there was a programming language called Basic, which stood for Beginner's All-purpose Symbolic Instruction Code. As the name suggests, Basic was intended to be as simple and accessible as possible for those unfamiliar with programming.
Then in 1991 Microsoft unveiled Visual Basic, a retooling of Basic that changed the way user interfaces were written. Visual Basic can still lay claim to being one of the most popular programming languages ever developed.
Visual Basic .NET is Microsoft's reengineering of Visual Basic for the .NET platform. VB.NET departs in some significant ways from earlier versions of Visual Basic. In fact, some early adopters of VB.NET started calling it VB.NOT. VB.NET has evolved into a full-fledged object-oriented commercial software development package. Yet VB.NET also retains some of the inherent simplicity of its predecessors.
VB.NET has a number of features that help it maintain backwards compatibility with Visual Basic 6 (VB6). Other features have been added specifically to adapt Visual Basic to object-oriented programming and the .NET platform.
VB.NET provides support in the language to find bugs early in the development process. This makes for code that is easier to maintain and programs that are more reliable. VB.NET does not support some features available in other languages (e.g., pointers) that make for unsafe code.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Visual Basic and .NET
Once upon a time there was a programming language called Basic, which stood for Beginner's All-purpose Symbolic Instruction Code. As the name suggests, Basic was intended to be as simple and accessible as possible for those unfamiliar with programming.
Then in 1991 Microsoft unveiled Visual Basic, a retooling of Basic that changed the way user interfaces were written. Visual Basic can still lay claim to being one of the most popular programming languages ever developed.
Visual Basic .NET is Microsoft's reengineering of Visual Basic for the .NET platform. VB.NET departs in some significant ways from earlier versions of Visual Basic. In fact, some early adopters of VB.NET started calling it VB.NOT. VB.NET has evolved into a full-fledged object-oriented commercial software development package. Yet VB.NET also retains some of the inherent simplicity of its predecessors.
VB.NET has a number of features that help it maintain backwards compatibility with Visual Basic 6 (VB6). Other features have been added specifically to adapt Visual Basic to object-oriented programming and the .NET platform.
VB.NET provides support in the language to find bugs early in the development process. This makes for code that is easier to maintain and programs that are more reliable. VB.NET does not support some features available in other languages (e.g., pointers) that make for unsafe code.
In the past, you might have learned a language like C or Java without much concern about the platform on which you would be programming. These cross-platform language were as comfortable on a Unix box as they were on a PC running Windows.
VB.NET, however, is a version of the Visual Basic language written specifically for .NET. While .NET may become cross-platform some day soon—a Unix port is already available—for now, the overwhelming majority of .NET programs will be written to run on a machine running Windows.
VB.NET represents a significant step forward for Visual Basic programmers. In the past, VB has been (unfairly) cast as a second-class "toy" language that was not up to the challenge of enterprise-level software development.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The .NET Platform
In July, 2000, Microsoft announced the .NET platform. .NET is a development framework that provides a fresh application programming interface (API) to the services and APIs of classic Windows operating systems, especially the Windows 2000 family, while bringing together a number of disparate technologies that emerged from Microsoft during the late 1990s. Among the latter are COM+ component services, the ASP web development framework, a commitment to XML and object-oriented design, support for new web services protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet, all integrated within the DNA architecture.
Microsoft says it is devoting 80% of its research and development budget to .NET and its associated technologies. The results of this commitment to date are impressive. For one thing, the scope of .NET is huge. The platform consists of four separate product groups:
  • A set of languages, including Visual Basic .NET, C#, JScript .NET, and Managed C++; a set of development tools, including Visual Studio .NET; a comprehensive class library for building web services and web and Windows applications; and the Common Language Runtime (CLR) to execute objects built within this framework.
  • A set of .NET Enterprise Servers, formerly known as SQL Server 2000, Exchange 2000, BizTalk 2000, and so on, that provide specialized functionality for relational data storage, email, B2B commerce, etc.
  • An offering of commercial web services, .NET My Services; for a fee, developers can use these services in building applications that require knowledge of user identity, etc.
  • New .NET-enabled non-PC devices, from cell phones to game boxes.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The .NET Framework
Microsoft .NET supports not only language independence, but also language integration. This means that you can inherit from classes, catch exceptions, and take advantage of polymorphism across different languages. The .NET Framework makes this possible with a specification called the Common Type System (CTS) that all .NET components must obey. For example, everything in .NET is an object of a specific class that derives from the root class called System.Object. The CTS supports the general concept of classes, interfaces, delegates (which support callbacks), reference types, and value types.
Additionally, .NET includes a Common Language Specification (CLS), which provides a series of basic rules that are required for language integration. The CLS determines the minimum requirements for being a .NET language. Compilers that conform to the CLS create objects that can interoperate with one another. The entire Framework Class Library (FCL) can be used by any language that conforms to the CLS. Complete coverage of the FCL classes is beyond the scope of this book. For more information on these classes, see VB.NET Language in a Nutshell (Roman, Petrusha, and Lomax, O'Reilly).
The .NET Framework sits on top of the operating system, which can be any flavor of Windows from Win 98 forward, and consists of a number of components.
Currently, the .NET Framework consists of:
  • Four official languages: VB.NET, C#, Managed C++, and JScript .NET
  • The Common Language Runtime, an object-oriented platform for Windows and web development that all these languages share
  • A number of related class libraries, collectively known as the Framework Class Library (FCL).
Figure 1-1 breaks down the .NET Framework into its system architectural components.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Compilation and the MSIL
In .NET, programs are not compiled into executable files; they are compiled into Microsoft Intermediate Language (MSIL) files, which the CLR then executes. The MSIL (often shortened to IL) files that Visual Basic .NET produces are identical to the IL files that other .NET languages produce; the platform is language-agnostic. A key fact about the CLR is that it is common; the same runtime supports development in VB.NET as well as in C#.
VB.NET code is compiled into IL when you build your project. The IL is saved in a file on disk. When you run your program, the IL is compiled again, using the Just In Time (JIT) compiler (a process often called JIT'ing). The result is machine code, executed by the machine's processor.
The standard JIT compiler runs on demand. When a method is called, the JIT compiler analyzes the IL and produces highly efficient machine code, which runs very fast. The JIT compiler is smart enough to recognize when the code has already been compiled, so as the application runs, compilation happens only as needed. As .NET applications run, they tend to become faster and faster, as the already-compiled code is reused.
The CLS means that all .NET languages produce very similar IL code. As a result, objects created in one language can be accessed and derived from another. Thus it is possible to create a base class in C# and derive from it in VB.NET.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The VB.NET Language
The VB.NET language is disarmingly simple, with relatively few keywords and a dozen built-in datatypes, but VB.NET is highly expressive when it comes to implementing modern programming concepts. VB.NET includes all the support for structured, component-based, object-oriented programming that one expects of a modern language.
At the heart of any object-oriented language is its support for defining and working with classes. Classes define new types, allowing you to extend the language to better model the problem you are trying to solve. VB.NET contains keywords for declaring new classes and their methods and properties, and for implementing encapsulation, inheritance, and polymorphism, the three pillars of object-oriented programming.
VB.NET also supports interfaces , a means of making a contract with a class for services that the interface stipulates. In VB.NET, a class can inherit from only a single parent, but a class can implement multiple interfaces. When it implements an interface, a VB.NET class in effect promises to provide the functionality the interface specifies.
VB.NET also provides support for structures. A structure is a restricted, lightweight type that, when instantiated, makes fewer demands on the operating system and on memory than a conventional class does. A structure can't inherit from a class or be inherited from, but a structure can implement an interface.
VB.NET provides component-oriented features, such as properties, events, and declarative constructs (called attributes ). Component-oriented programming is supported by the CLR's support for storing metadata with the code for the class. The metadata describes the class, including its methods and properties, as well as its security needs and other attributes, such as whether it can be serialized; the code contains the logic necessary to carry out its functions. A compiled class is thus a self-contained unit; therefore, a hosting environment that knows how to read a class' metadata and code needs no other information to make use of it. Using VB.NET and the CLR, it is possible to add custom metadata to a class by creating custom attributes. Likewise, it is possible to read class metadata using CLR types that support reflection.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started: "Hello World"
It is a time-honored tradition to start a programming book with a "Hello World" program. In this chapter, we will create, compile, and run a simple "Hello World" program written in Visual Basic .NET. The analysis of this brief program will introduce key features of the Visual Basic .NET language.
Example 2-1 illustrates the fundamental elements of a very simple Visual Basic .NET program.
Example 2-1. A simple "Hello World" program in VB.NET
   Module HelloWorld
   ' every console app starts with Main
      Sub Main( )
         System.Console.WriteLine("Hello World")
      End Sub
   End Module
That is the entire program. Compiling and running it displays the words "Hello World" at the console.
The single greatest challenge when learning to program is that you must learn everything before you can learn anything. Even this simple program uses many features of the language that will be discussed in coming chapters, including statements, methods, objects, strings, inheritance, blocks, libraries, and polymorphism.
This chapter provides a whirlwind tour of a number of these concepts. I'll then spend the rest of the book expanding on these areas and showing how they can be applied to create .NET applications.
Each program consists of a series of statements, which are instructions to the complier. In VB.NET, as in previous versions of Visual Basic, every statement ends with a carriage return/linefeed; you create one by pressing the Enter key.
The first line in Example 2-1 defines a programming unit known as a module . In this case, the module is named HelloWorld:
Module HelloWorld
You begin each module definition using the Module keyword, as in the preceding code line. Likewise, you end each module definition with this line:
End Module
Within the HelloWorld module you define a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Examining Your First Program
The single greatest challenge when learning to program is that you must learn everything before you can learn anything. Even this simple program uses many features of the language that will be discussed in coming chapters, including statements, methods, objects, strings, inheritance, blocks, libraries, and polymorphism.
This chapter provides a whirlwind tour of a number of these concepts. I'll then spend the rest of the book expanding on these areas and showing how they can be applied to create .NET applications.
Each program consists of a series of statements, which are instructions to the complier. In VB.NET, as in previous versions of Visual Basic, every statement ends with a carriage return/linefeed; you create one by pressing the Enter key.
The first line in Example 2-1 defines a programming unit known as a module . In this case, the module is named HelloWorld:
Module HelloWorld
You begin each module definition using the Module keyword, as in the preceding code line. Likewise, you end each module definition with this line:
End Module
Within the HelloWorld module you define a method , or programming routine, called Main( ). The Main( ) method is the "entry point" for every VB.NET console application; it is where your program begins. Within the HelloWorld module, the Main( ) method is defined from lines 3 through 5. Notice the Sub keyword to signal the beginning of the subroutine and the End Sub line to conclude the method:
Sub Main( )
    System.Console.WriteLine("Hello World")
End Sub
Typically, one method calls another. The called method will do work, and it can return a value to the calling method. In VB.NET, as in previous versions of VB, methods come in two flavors: a method that returns a value is called a function ; a method that does not return a value is called a sub (subroutine).
Main( ) is called by the operating system (when the program is invoked). Every method name is followed by opening and closing parentheses:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Writing and Building Your Programs
There are two obvious ways to enter, compile, and run the programs in this book. You can enter the text into a text editor like Notepad and then use the command-line compiler, or you can use the Visual Studio .NET Integrated Development Environment (IDE) to write the code and then request that the IDE call the compiler for you.
The job of the compiler is to turn your source code into a working program. It turns out to be just slightly more complicated than that because .NET uses an intermediate language called Microsoft Intermediate Language (MSIL, sometimes abbreviated to IL). The compiler reads your source code and produces IL. The .NET Just In Time (JIT) compiler then reads your IL code and produces an executable application in memory.
You can enter source code like the "Hello World" program from Example 2-1 in any text editor, such as Notepad. You then save the code in a text file. For instance, you might name the file containing the "Hello World" program HelloWorld.vb.
You can then compile the source code by opening the Visual Studio .NET Command Prompt. In order to ensure that your compiler environment variables are set properly (so that your compiler will work properly) you will want to open a special DOS box provided in the .NET SDK. After installing the SDK, you will typically find this program at:
"C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Tools\vsvars32.bat" 
I recommend that you save a shortcut to this on your desktop, but you can also open the Visual Studio .NET Command Prompt by using the menu sequence
Start -> Programs -> Microsoft Visual Studio .NET 2003 -> Visual Studio .NET Tools -> 
Visual Studio .NET Command Prompt
On the command line, enter the name of the VB.NET compiler program, vbc, passing in the source, as in the following:
vbc HelloWorld.vb
The Microsoft VB.NET compiler will compile your code; when you display the directory you'll find that the compiler has produced an executable file called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the VS.NET Debugger
Arguably, the single most important tool in any development environment is the debugger. The Visual Studio .NET debugger is very powerful, and it will be well worth whatever time you put into learning how to use it well. That said, the fundamentals of debugging are very simple. The three key skills are:
  • How to set a breakpoint and how to run to that breakpoint
  • How to step into and over method calls
  • How to examine and modify the value of variables, member data, and so forth
This chapter does not reiterate the entire debugger documentation, but these skills are so fundamental that it does provide a crash (pardon the expression) course.
The debugger can accomplish the same thing in many ways—typically via menu choices, buttons, and so forth. The simplest way to set a breakpoint is to click in the lefthand margin. The IDE will mark your breakpoint with a red dot, as shown in Figure 2-6.
Figure 2-6: A breakpoint
Discussing the debugger requires code examples. The code shown here is from Chapter 6, and you are not expected to understand how it works yet (though if you program in VB6, you'll probably get the gist of it).
To run the debugger you can choose Debug->Start or just press F5. The program will compile and run to the breakpoint, at which time it will stop and a yellow arrow will indicate the next statement for execution, as in Figure 2-7.
Figure 2-7: The breakpoint hit
After you've hit your breakpoint it is easy to examine the values of various objects. For example, you can find the value of the variable
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Language Fundamentals
Chapter 2 demonstrates a very simple Visual Basic .NET program. Nonetheless, there is sufficient complexity in creating even that little program that some of the pertinent details had to be skipped over. This chapter illuminates these details by delving more deeply into the syntax and structure of the Visual Basic .NET language itself.
This chapter discusses the type system in Visual Basic .NET, drawing a distinction between built-in types (Integer, Boolean, etc.) and user-defined types (types you create, such as classes and interfaces). The chapter also covers programming fundamentals such as how to create and use variables and constants. It then goes on to introduce enumerations, strings, identifiers, expressions, and statements.
The second part of the chapter explains and demonstrates the use of branching, using statements such as If, Do, Do...While, and For. Also discussed are operators, including the assignment, logical, relational, and mathematical operators. Although Visual Basic .NET is principally concerned with the creation and manipulation of objects, it is best to start with the fundamental building blocks: the elements from which objects are created. These include the built-in types that are an intrinsic part of the Visual Basic .NET language as well as the syntactic elements of Visual Basic .NET.
If you're an experienced VB6 programmer, you might be tempted to skim through this chapter. However, you should take note of the following significant differences between VB6 and VB.NET:
  • The Visual Basic .NET equivalent to the VB6 Currency type is the Decimal type. While these two types are for most purposes interchangeable, they differ in terms of precision. The Decimal type is a fixed-precision number with up to 28 digits, plus the position of the decimal point. Decimal values require the suffix "m" or "M".
  • In VB.NET, the VB6 Variant type is eliminated.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
VB.NET Versus VB6
If you're an experienced VB6 programmer, you might be tempted to skim through this chapter. However, you should take note of the following significant differences between VB6 and VB.NET:
  • The Visual Basic .NET equivalent to the VB6 Currency type is the Decimal type. While these two types are for most purposes interchangeable, they differ in terms of precision. The Decimal type is a fixed-precision number with up to 28 digits, plus the position of the decimal point. Decimal values require the suffix "m" or "M".
  • In VB.NET, the VB6 Variant type is eliminated.
  • While in VB6, Char is a single-character String, in Visual Basic .NET Char is a type in its own right.
  • Microsoft no longer recommends Hungarian notation in public identifiers. Meaningful identifiers should be used (studentAge rather than x01) but no type-identifier prefix is needed or recommended.
  • In VB.NET, enumerations are formal types, and so an explicit conversion is required to convert between an Enum type and an intrinsic type (such as Integer, Boolean, etc.).
  • In VB6 enumerations are just aliases for integer values. In VB.NET, enumerations are actual types, and you must access enumerated constants using the fully qualified name of the enumeration (e.g., Temperature.FreezingPoint).
  • In VB.NET, there is no Set statement; however properties have Set and Get accessors, as described in Chapter 5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
VB.NET Types
Visual Basic .NET can (and should) be treated as a strongly typed language. In a strongly typed language you must declare the type of each object you create (e.g., Integer, Decimal, String, Window, Button, etc.) and the compiler will help you prevent bugs by enforcing that only data of the right type is assigned to those objects. You tell the compiler you want Visual Basic .NET to be strongly typed by adding the line:
Option Strict On
to the top of every source code file. While this is optional it is good programming practice, and this book will assume that Option Strict is set On from now on. You can make this the default in Visual Studio .NET (starting in Version 1.1.) by choosing the menu items Tools->Options->Projects->VB Defaults and setting the default to Option Strict On.
The type of an object signals to the compiler the size of that object (e.g., Integer indicates an object of 4 bytes) and its capabilities (e.g., Buttons can be drawn, pressed, and so forth).
Like C++ and Java, Visual Basic .NET divides types into two sets: intrinsic (built-in) types that the language offers and user-defined types that the programmer defines.
Visual Basic .NET also divides the set of types into two other categories: value types and reference types. The principal difference between value and reference types is the manner in which their values are stored in memory. A value type holds its actual value in memory allocated on the stack (or it is allocated as part of a larger reference type object). The address of a reference type variable sits on the stack, but the actual object is stored on the heap.
If you have a very large object, putting it on the heap has many advantages. Chapter 5 discusses the various advantages and disadvantages of working with reference types; the current chapter focuses on the intrinsic value types available in Visual Basic .NET.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Identifiers
Identifiers are names that programmers choose for their types, methods, variables, constants, objects, and so forth. An identifier must begin with a letter or an underscore.
The Microsoft naming conventions suggest using Camel notation (initial lowercase such as someName) for variable names (see Section 3.4) and Pascal notation (initial uppercase such as SomeOtherName) for method names and most other identifiers. (Examples are provided later in this chapter and in subsequent chapters.)
Identifiers cannot clash with keywords. Thus, you cannot create a variable named Integer or Module. In addition, Visual Basic .NET identifiers are not case-sensitive, so myVariable and MyVariable are treated as the same variable names.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables and Constants
A variable is a storage location with a type. The type will be one of the intrinsic types (variables of user-defined types are called objects, and are explained in Chapter 5). In the examples in Section 3.2.3, both myInteger and myDouble are variables. Variables can have values assigned to them, and those values can be changed programmatically.
You create a variable by declaring its type and then giving it a name. You can initialize the variable when you declare it, and you can assign a new value to that variable at any time, changing the value held in the variable. Example 3-1 initializes the variable myInteger with the value 7, displays that value, reassigns the variable with the value 5, and displays it again.
Example 3-1. Initializing and assigning a value to a variable
Option Strict On
Imports System

Module Module1
    Sub Main( )
        Dim myInteger As Integer = 7
        Console.WriteLine("Initialized, myInteger: {0}", _
            myInteger)
        myInteger = 5
        Console.WriteLine("After assignment, myInteger: {0}", _
            myInteger)
    End Sub
End Module

Output:
Initialized, myInteger: 7
After assignment, myInteger: 5
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Whitespace
In the Visual Basic .NET language, spaces and tabs are considered to be "whitespace" (so named because you see only the white of the underlying "page"). Extra whitespace is generally ignored in Visual Basic .NET statements. Thus, you can write:
myVariable = 5
or:
myVariable    =                        5
and the compiler will treat the two statements as identical. In fact, Visual Studio .NET will automatically discard the extra white space and close up the second version so that it resembles the first!
The exception to this rule is that whitespace within strings is not ignored. If you write:
Console.WriteLine("Hello World")
each space between "Hello" and "World" is treated as another character in the string.
Most of the time the use of whitespace is intuitive. The key is to use whitespace to make the program more readable to the programmer; the compiler is indifferent.
However, there are instances in which the use of whitespace is quite significant. Although the expression:
Dim x As Integer = 5
is the same as:
Dim x As Integer=5
it is not the same as:
Dimx As Integer = 5
The compiler knows that the whitespace on either side of the assignment operator is extra, but the whitespace between the keyword Dim and the identifier x is not extra, and is required. This is not surprising; the whitespace allows the compiler to parse the keyword Dim rather than some unknown term Dimx. You are free to add as much or as little whitespace between Dim and x as you care to, but there must be at least one whitespace character (typically a space or tab).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Statements
In Visual Basic .NET a complete program instruction is called a statement . Programs consist of sequences of Visual Basic .NET statements. Each statement must end with a new line:
Dim x As Integer       ' a statement
x = 23                 ' another statement
Dim y As Integer = x   ' yet another statement
It is possible to combine two (or more) statements on a single line by separating the statements with the colon operator:
Dim x As Integer = 23 : Dim y As Integer = 25
While this is legal, it is uncommon because it makes the code more difficult to read.
A statement that evaluates to a value (e.g., to a Boolean value) is called an expression .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Branching
Visual Basic .NET statements are evaluated in order. The compiler starts at the beginning of a statement list and makes its way to the bottom. This would be entirely straightforward, and terribly limiting, were it not for branching. There are two types of branches in a Visual Basic .NET program: unconditional branching and conditional branching .
Program flow is also affected by looping and iteration statements, which are signaled by the keywords If, Select Case, For, Do, While, and For Each. Iteration is discussed later in this chapter, and For Each is considered in Chapter 3. For now, let's consider some of the more basic methods of conditional and unconditional branching.
An unconditional branch is created by invoking a method. When the compiler encounters the name of a method it stops execution in the current method and branches to the newly "called" method. When that method returns a value, execution picks up in the original method on the line just below the method call. Example 3-4 illustrates.
Example 3-4. Calling a method
Option Strict On
Imports System
Module Module1
   Sub Main( )
      Console.WriteLine("In Main! Calling SomeMethod( )...")
      SomeMethod( )
      Console.WriteLine("Back in Main( ).")
   End Sub 'Main

   Sub SomeMethod( )
      Console.WriteLine("Greetings from SomeMethod!")
   End Sub 'SomeMethod

End Module

Output:
In Main! Calling SomeMethod( )...
Greetings from SomeMethod!
Back in Main( ).
Program flow begins in Main( ) and proceeds until SomeMethod( ) is invoked (invoking a method is sometimes referred to as "calling" the method). At that point program flow branches to the method. When the method completes, program flow resumes at the next line after the call to that method.
You can create an unconditional branch by using one of the unconditional branch keywords:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Iteration (Looping) Statements
There are many situations in which you will want to do the same thing again and again, perhaps slightly changing a value each time you repeat the action. This is called iteration or looping. Typically, you'll iterate (or loop) over a set of items, taking the same action on each. This is the programming equivalent to an assembly line. On an assembly line, you might take a hundred car bodies and put a windshield on each one as it comes by. In an iterative program, you might work your way through a collection of text boxes on a form, retrieving the value from each in turn and using those values to update a database.
VB.NET provides an extensive suite of iteration statements, including Do, For, and For Each. You can also create a loop by using a statement called Goto. This chapter considers the use of Goto, Do, and For. However, you'll have to wait until Chapter 3 to learn more about For Each.
Goto is the most primitive kind of unconditional branching statement, and it is not much used in modern programming. Its most common usage was to create looping statements, and in fact, the Goto statement is the seed from which all other looping statements have been germinated. Unfortunately, it is a semolina seed, producer of spaghetti code and endless confusion.
Programs that use Goto statements jump around a great deal. Goto can cause your method to loop back and forth in ways that are difficult to follow.
If you were to try to draw the flow of control in a program that makes extensive use of Goto statements, the resulting morass of intersecting and overlapping lines might look like a plate of spaghetti; hence the term "spaghetti code." Spaghetti code is a contemptuous epithet; no one wants to write spaghetti code.
Most experienced programmers properly shun the Goto statement, but in the interest of completeness, here's how you use it:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Operators
An operator is a symbol (e.g., =, +, >, &) that causes VB.NET to take an action. That action might be an assignment of a value to a variable, the addition of two values, a comparison of two values, concatenation of strings, etc.
In the previous sections, you've seen a number of operators at work. For example, the assignment operator (=) has been used to assign a value to a variable:
Dim myVariable As Integer
myVariable = 15
In the code shown above, the value 15 is assigned to the Integer variable myVariable. In the section on branching you saw more sophisticated operators, such as the greater-than comparison operator (>) used to compare two values:
If valueOne > valueTwo Then
The preceding If statement compares valueOne with valueTwo; if the former is larger than the latter, the test evaluates true, and the If statement executes.
The following sections will consider many of the operators used in VB.NET in some detail.
VB.NET uses seven mathematical operators: five for standard calculations (+, -, *, /, and \), a sixth to return the remainder when dividing integers (Mod), and a seventh for exponential operations (^). The following sections consider the use of these operators.

Section 3.9.1.1: Simple arithmetic operators (+, -, *, /, \)

VB.NET offers five operators for simple arithmetic: the addition (+), subtraction (-), and multiplication (*) operators work as you might expect. Adding two numbers returns their sum, subtracting returns their difference, and multiplying returns their product.
VB.NET offers two division operators: / and \. The forward slash or right-facing division operator (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Logical Operators Within Conditionals
If statements test whether a condition is true. Often you will want to test whether two conditions are both true, or only one is True, or neither is True. VB.NET provides a set of logical operators for this, as shown in Table 3-3. This table assumes two variables, x and y, in which x has the value 5, and y the value 7.
Table 3-3: Logical operators (assumes x = 5 and y = 7)
Operator
Given this statement:
The expressionevaluates to:
Logic
And
x = 3 And y = 7
False
Both must be true to evaluate true.
Or
x = 3 Or y = 7
True
Either or both must be true to evaluate true.
XOr
X = 5 XOr y = 7
False
True only if one (and only one) statement is true.
Not
Not x = 3
True
Expression must be false to evaluate true.
The And operator tests whether two statements are both true. The first line in Table 3-3 includes an example that illustrates the use of the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Object-Oriented Programming
Windows and web programs are enormously complex. Programs present information to users in graphically rich ways, offering complicated user interfaces, complete with drop-down and pop-up menus, buttons, listboxes, and so forth. Behind these interfaces, programs model complex business relationships, such as those among customers, products, orders, and inventory. You can interact with such a program in hundreds, if not thousands, of different ways, and the program must respond appropriately every time.
To manage this enormous complexity, programmers have developed a technique called object-oriented programming. It is based on a very simple premise: you manage complexity by modeling its essential aspects. The closer your program models the problem you are trying to solve, the easier it is to understand (and thus to write and to maintain) that program.
Programmers refer to the problem you are trying to solve and all the information you know about that problem as the problem domain . For example, if you are writing a program to manage the inventory and sales of a company, the problem domain would include everything you know about how the company acquires and manages inventory, makes sales, handles the income from sales, tracks sales figures, and so forth. The sales manager and the stock room manager would be problem domain experts who can help you understand the problem domain.
A well-designed object-oriented program will be filled with objects from the problem domain. At the first level of design, you'll think about how these objects interact, and what their state, capabilities, and responsibilities are.
State
A programmer refers to the current conditions and values of an object as that object's state. For example, you might have an object representing a customer. The customer's state includes the customer's address, phone number, and email, as well as the customer's credit rating, recent purchase history, and so forth.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Models
Humans are model-builders. We create models of the world to manage complexity and to help us understand problems we're trying to solve. You see models all the time. Maps are models of roadways. Globes are models of the Earth. Chemical symbols are models of chemical interactions. Atomic models are representations of the interaction of sub-atomic particles.
Models are simplifications. There is little point to a model that is as complex as the object in the problem domain. If you had a map of the United States that had every rock, blade of grass, and bit of dirt in the entire country, the map would have to be as big as the country itself. Your road atlas of the U.S. eschews all sorts of irrelevant detail, focusing only on those aspects of the problem domain (e.g., the country's roads) that are important to solving the problem (e.g., getting from one place to another). If you want to drive from Boston to New York City, you don't care where the trees are; you care where the exits and interchanges are located. Therefore, the network of roads is what appears on the atlas.
Albert Einstein once said, "Things should be made as simple as possible, but not any simpler." A model must be faithful to those aspects of the problem domain that are relevant. For example, a road map must provide accurate relative distances. The distance from Boston to New York must be proportional to the actual driving distance. If one inch represents 25 miles at the start of the trip, it must represent 25 miles throughout the trip, or the map will be unusable.
A good object-oriented design is an accurate model of the problem you are trying to solve. Your design choices will influence not only how you solve the problem, but in fact they will influence how you think about the problem. A good design, like a good model, allows you to examine the relevant details of the problem without confusion.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Classes and Objects
The most important metaphors in object-oriented programming are the class and the object.
A class defines a new type of thing. The class defines the common characteristics of every object of that new type. For example, you might define a class Car. Ever car will share certain characteristics (wheels, brakes, accelerator, and so forth). You drive a particular car, but your car and my car both belong to the class of Cars; they are of type Car.
An object is an individual instance of a type. Each individual car (your particular car, my particular car) is an instance of the class Car, and thus is an object. An object is just a thing.
We perceive the world to be composed of things. Look at your computer. You do not see various bits of plastic and glass amorphously merging with the surrounding environment. You naturally and inevitably see distinct things: a computer, a keyboard, a monitor, speakers, pens, paper. Things.
More importantly, even before you decide to do it, you've categorized these things. You immediately classify the computer on your desk as a specific instance of a type of thing: this computer is one of the type Computer. This pen is an instance of a more general type of thing, Pens. It is so natural you can't avoid it, and yet the process is so subtle, it's difficult to articulate. When I see my dog Milo, I can't help but see him as a dog, not just as an individual entity. Milo is an instance, Dog is a class.
The theory behind object-oriented programming is that for computer programs to accurately model the world, the programs should reflect this human tendency to think about things and types of things. In VB.NET you do that by creating a class to define a type and creating an object to model a thing.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Class Relationships
The heart of object-oriented design is establishing relationships among the classes. Classes interact and relate to one another in various ways.
The simplest interaction is when a method in one class is used to call a method in a second class. For example, the Manager class might have a method that calls the UpdateSalary( ) method on an object of type Employee. We then say that the Manager class and the Employee class are associated. Association among classes simply means they interact.
Some complicated types are composed of other types. For example, an automobile might be composed of wheels, engine, transmission, and so forth. You might model this by creating a Wheel class, an Engine class, and a Transmission class. You could then create an Automobile class, and each automobile would have four instances of the Wheel class, and one instance each of the Engine and Transmission class. Another way to view this relationship is to say that the Automobile class aggregates the Wheel, Engine, and Transmission classes.
This process of aggregation (or composition) allows you to build very complex classes from relatively simple classes. The .NET Framework provides a String class to handle text strings. You might create your own Address class out of five text strings (address line 1, address line 2, city, state, and zip). You might then create a second class, Employee, that has an instance of Address as one of its members.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Three Pillars of Object-Oriented Programming
Object-oriented programming is built on three sturdy pillars: encapsulation , specialization, and polymorphism.
Each class should be fully encapsulated; that is, it should define the state and responsibilities of that type. For example, if you create an Employee object, that Employee object should fully define all there is to know, from the perspective of your program, about each Employee. You do not, typically, want to have one class that defines the Employee's work information, and a second, unrelated class that defines the Employee's contact information. Instead, you want to encapsulate all this information inside the Employee class, perhaps by aggregating the contact information as a member of the Employee class.
Specialization allows you to establish hierarchical relationships among your classes. For example, you can define a Manager to be a specialized type of an Employee and an Employee to be a specialized type of Person. This allows you to leverage the state and abilities of an Employee object in the more specialized form of the Manager.
Polymorphism allows you to treat a group of objects in a similar way and have the objects sort out how to implement the programming instructions. For instance, suppose you have a collection of Employee objects and you want to tell each Employee to give herself a raise. It turns out that Employees get a straight 5% raise, while raises for Managers are determined by how well they've fulfilled their annual objectives. With polymorphism, you can tell each object in the collection to give itself a raise, and the right thing happens regardless of the real type of the object. That is, each employee gets 5%, while each manager gets the appropriate raise based on objectives.
The first pillar of object-oriented programming is encapsulation . The idea behind encapsulation is that you want to keep each type or class discreet and self-contained. This allows you to change the implementation of one class without affecting any other class.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object-Oriented Analysis and Design
The steps to take before programming anything are analysis and design. Analysis is the process of understanding and detailing the problem you are trying to solve. Design is the actual planning of your solution.
With trivial problems (e.g., computing the Fibonacci series), you may not need an extensive analysis period, but with complex business problems, the analysis process can take weeks or even months. One powerful analysis technique is to create what are called use-case scenarios, in which you describe in some detail how the system will be used. Among the other considerations in the analysis period are determining your success factors (how do you know if your program works) and writing a specification of your program's requirements.
Once you've analyzed the problem, you design the solution. Key to the design process is imagining the classes you will use and their inter-relationships. You might design a simple program on the fly, without this careful planning; but in any serious business application, you will want to take some time to think through the issues.
There are many powerful design techniques you might use, most of which are beyond the scope of this book. One interesting controversy that has arisen recently is between traditional object-oriented design on the one hand and eXtreme programming on the other.
There are other competing approaches as well. How much time you put into these topics will depend, in large measure, on the complexity of the problems you are trying to solve, and the size of your development team.
My personal approach to managing complexity is to keep team size very small. I have worked on large development teams, and over the years I've come to believe that the ideal size is three. Three highly skilled programmers can be incredibly productive, and with three you don't need a manager. Three people can have only one conversation at a time. Three people can never be evenly split on a decision. One day I'll write a book on programming in teams of three, but this isn't it, and so we'll stay focused on VB.NET programming, rather than on design debates.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Classes and Objects
Chapter 3 discusses the primitive types built into the VB.NET language, such as Integer, Long, and Single. The true power of VB.NET, however, lies in its capacity to let the programmer define new types to suit particular problems. It is this ability to create new types that characterizes an object-oriented language. You specify new types in VB.NET by declaring and defining classes.
Particular instances of a class are called objects. The difference between a class and an object is the same as the difference between the concept of a Dog and the particular dog who is shedding on your carpet as you read this. You can't play fetch with the definition of a Dog, only with an instance.
A Dog class describes what dogs are like: they have weight, height, eye color, hair color, disposition, and so forth. They also have actions they can perform, such as eat, walk, bark, and sleep. A particular dog (such as my dog Milo) will have a specific weight (62 pounds), height (22 inches), eye color (black), hair color (yellow), disposition (angelic), and so forth. He is capable of all the actions—methods, in programming parlance—of any dog (though if you knew him you might imagine that eating is the only method he implements).
The huge advantage of classes in object-oriented programming is that classes encapsulate the characteristics and capabilities of a type in a single, self-contained unit. Suppose, for instance, you want to sort the contents of a Windows listbox control. The listbox control is defined as a class. One of the properties of that class is that it knows how to sort itself. Sorting is encapsulated within the class, and the details of how the listbox sorts itself are not made visible to other classes. If you want a listbox sorted, you just tell the listbox t