BUY THIS BOOK
Add to Cart

Print Book $34.95


Add to Cart

Print+PDF $45.44

Add to Cart

PDF $27.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint or License this content?


Learning Visual Basic .NET
Learning Visual Basic .NET

By Jesse Liberty
Book Price: $34.95 USD
£24.95 GBP
PDF Price: $27.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Visual Basic .NET and .NET Programming
Learning Visual Basic .NET was written to introduce the .NET version of the Visual Basic language specifically, and the .NET development platform more generally, to programmers with little or no object-oriented programming experience. Along the way, you will learn a great deal about writing high-quality, industrial-strength programs for .NET.
In this brief introduction, you will learn the basics of the Visual Basic .NET language. You will also learn some of the concepts integral to object-oriented programming, which has revolutionized how web and Windows applications are developed.
The goal of this book is to go beyond the syntax of VB.NET (the keywords and punctuation of the language) to examine the semantics of .NET programming with VB.NET (the meaning and structure of the code). VB.NET and the .NET Framework are built on the concepts of object-oriented design and programming, and these concepts will be explained as the book progresses to provide a deeper insight into how .NET programs are organized.
Long, long ago, and far, far away, in a little-known universe of primitive computing, there was a language called Basic, which stood for Beginner's All-purpose Symbolic Instruction Code. Basic was designed to be as simple and accessible as possible for those unfamiliar with programming.
In 1991 Microsoft unveiled Visual Basic and changed the way graphical user interfaces were written. Visual Basic can lay claim to being one of the most popular programming languages ever invented.
Visual Basic .NET (VB.NET) is a reengineering of this venerable language, which departs in 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 retain backwards compatibility with Visual Basic 6 (VB6). Other features have been added specifically to adapt Visual Basic to object-oriented programming and to the .NET platform.
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
Long, long ago, and far, far away, in a little-known universe of primitive computing, there was a language called Basic, which stood for Beginner's All-purpose Symbolic Instruction Code. Basic was designed to be as simple and accessible as possible for those unfamiliar with programming.
In 1991 Microsoft unveiled Visual Basic and changed the way graphical user interfaces were written. Visual Basic can lay claim to being one of the most popular programming languages ever invented.
Visual Basic .NET (VB.NET) is a reengineering of this venerable language, which departs in 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 retain backwards compatibility with Visual Basic 6 (VB6). Other features have been added specifically to adapt Visual Basic to object-oriented programming and to 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 many 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 languages 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.
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, a development framework that provides a new way to create Windows applications. However, .NET goes beyond traditional Windows programming to facilitate creating web applications quickly and easily. And VB.NET is one of the premier languages Microsoft supports for development in this new and exciting .NET space.
Reports are that Microsoft is devoting 80% of its research and development budget to .NET and its associated technologies. The results of this commitment are impressive. For one thing, the scope of .NET is huge. The platform consists of three separate product groups:
  • A set of languages, including Visual Basic .NET and C#; a set of development tools, including Visual Studio .NET; and powerful tools for building applications, including the Common Language Runtime (CLR) a platform for compiling, debugging, and executing .NET applications.
  • 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.
  • New .NET-enabled non-PC devices, from cell phones to game boxes.
The VB.NET language can be used to develop three types of applications you can run on your Windows computer:
  • Console applications display no graphics
  • Windows applications use the standard Windows interface
  • Web applications can be accessed with a browser
This book will focus primarily on the basics of the VB.NET language, mostly using simple console applications to illustrate language fundamentals.
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
Central to the .NET platform is a development environment known as the .NET Framework. The Framework specifies how .NET programming constructs such as intrinsic types, classes, and interfaces are implemented. You will learn about these constructs in the chapters ahead.
The .NET Framework sits on top of any flavor of the Windows operating system. The most important components of the Framework are the Common Language Runtime (CLR), described in the preceding section, and the so-called Framework Class Library (FCL), which provides an enormous number of predefined types or classes for you to use in your programs. You will learn how to define your own classes in Chapter 8. Complete coverage of all 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).
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, 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.
The goal of VB.NET is to provide a simple, safe, object-oriented, Internet-centric, high-performance language for .NET development. VB.NET is simple because there are relatively few keywords. This makes it easy to learn and easy to adapt to your specific needs.
Keywords are special words reserved by the language and that have a specific meaning within all VB.NET programs. Keywords include If, While, For, and so forth. You'll learn about these keywords in the coming chapters.
VB.NET is considered safe because it 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 provides full support for object-oriented programming. This book will explain not only how to write object-oriented programs, but will explain why object-oriented programming has become so popular. The short answer is this: programs are becoming increasingly complex, and object-oriented programming techniques help you manage that complexity.
VB.NET was developed for .NET, and .NET was designed for developing web and web-aware programs. The Internet is a primary resource in most .NET applications.
Finally, VB.NET was designed for professional high-performance programming.
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 Structure of VB.NET Applications
At the most fundamental level, a VB.NET application consists of source code. Source code is human-readable text written in a text editor. A text editor is like a word processor, but it puts no special characters into the file to support formatting, only the text. A classic text editor is Notepad.
Example 1-1 shows an example of a very simple source code file.
Example 1-1. A source code file
   Module HelloWorld
      ' every console app starts with Main
      Sub Main( )
        System.Console.WriteLine("Hello world!")
      End Sub
   End Module
This program is explained in detail in Chapter 2. For now, observe that the program itself is readable: it is in normal text. The words may be strange and the layout unusual, but there are no special characters; just the normal text produced by your keyboard.
Once you write your program in an editor, you must compile it. For that you need a compiler. You will learn how to use the VB.NET compiler in Chapter 2. Once compiled, your program must be run and tested.
While you can perform all of these tasks using Notepad (or another text editor) and various command-line tools, your programming life will be much easier if you use the Integrated Development Environment (IDE) called Visual Studio .NET. VS.NET was designed with .NET development in mind and greatly simplifies the writing of VB.NET program 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!
The Development Environment
The Visual Studio .NET Integrated Development Environment provides enormous advantages to the VB.NET programmer. This book tacitly assumes that you'll use Visual Studio .NET for your work. However, the discussion focuses more on the language and the platform than on the tools.
Nonetheless, Chapter 4 provides a good introduction to the IDE in some detail. Chapter 10 returns to the IDE to examine the debugger, which will help you find and correct problems in your 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!
Chapter 2: Getting Started with VB.NET
You can use VB.NET to create three different types of programs:
  • Web applications
  • Windows applications
  • Console applications
The .NET platform is web-centric. The VB.NET language was developed to allow .NET programmers to create very large, powerful, high-quality web applications quickly and easily. The .NET technology for creating web applications is called ASP.NET.
ASP.NET, the next generation from ASP (Active Server Pages), is composed of two Microsoft development technologies: Web Forms and Web Services. While the development of fully realized web applications using these technologies is beyond the scope of this book, learning the basics of the VB.NET language will certainly get you started in the right direction. VB.NET is generally acknowledged to be one of the languages of choice for ASP.NET development.
Typically, you'll create an ASP.NET application when you want your program to be available to end users on any platform (e.g., Windows, Mac, Unix). By serving your application over the Web, end users can access your program with any browser.
When you want the richness and power of a native application running directly on the Windows platform, alternatively you might create a desktop-bound Windows application. The .NET tools for building Windows applications are called Windows Forms; a detailed analysis of this technology is also beyond the scope of this book.
However, if you don't need a Graphical User Interface (GUI) and just want to write a simple application that talks to a console window (i.e., what we used to call a DOS box), you might consider creating a console application. This book makes extensive use of console applications to illustrate the basics of the VB.NET language.
Web, Windows, and console applications are described and illustrated in the following pages.
Console applications
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's in a Program?
A program consists of English-language instructions called source code. The syntax for these instructions is strictly defined by the language. Source code consists of a series of statements. A statement is an instruction to the complier. Each instruction must be formed correctly, and one task you'll face when learning VB.NET will be to learn the correct syntax of the language. For example, in VB.NET every statement ends with a carriage return or linefeed.
Each instruction has a semantic meaning that expresses what it is you are trying to accomplish. Although you must follow the syntax, the semantics of the language are far more important in developing effective object-oriented programs. This book will provide insight into both the syntax and the semantics of good VB.NET programs.
You will save the source code you write in a text file. You can write this source code file using any simple text editor (such as Notepad), or you can use the Visual Studio .NET Integrated Development Environment (IDE). Visual Studio .NET is described in Chapter 4.
Once you write your program, you compile it using the VB.NET compiler. The end result of compiling the program is an application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Your First Program: Hello World
In this chapter, you will create a very simple application that does nothing more than display the words "Hello World" to your monitor. This basic console application is the traditional first program for learning any new language; it demonstrates some of the basic elements of a VB.NET program.
Once you write your "Hello World" program and compile it, this chapter will provide a line-by-line analysis of the source code. This analysis gives something of a preview of the language, the fundamentals of which are described much more fully in Chapter 5.
As explained earlier, you can create VB.NET programs with any text editor. You can, for example, create each of the three programs shown previously (in Figure 2-1, Figure 2-2, and Figure 2-3) with Notepad. To demonstrate that this is possible, you'll write your very first VB.NET program using Notepad.
Begin by opening Notepad and typing in the program exactly as shown in Example 2-1.
Example 2-1. Hello World in Notepad
Module HelloWorld
   ' every console app starts with Main
   Sub Main( )
      System.Console.WriteLine("Hello world!")
   End Sub
End Module
That is the entire program. Save it to your disk as a file called helloworld.vb.
We'll examine this program in some detail in just a moment. First, however, it must be compiled.
Once you save your program to disk, you must compile the code to create your application. Compiling your source code means running a compiler and passing in the source code file. You run the compiler by opening a command prompt (DOS box) and entering the program name vbc. Then you "pass in" your source code file by entering the filename on the command line, as in the following:
vbc helloworld.vb
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.
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 "Hello World" program uses many features of the language that will be discussed in coming chapters, including classes, namespaces, statements, static methods, objects, strings, inheritance, blocks, libraries, and even something called polymorphism!
It is as if you were learning to drive a car. You must learn to steer, accelerate, brake, and understand the flow of traffic. Right now we're going to get you out on the highway and just let you steer for a while. Over time you'll learn how to speed up and slow down. Along the way you'll learn to set the radio and adjust the heat so that you'll be more comfortable. In no time you'll be driving, and then won't your parents begin to worry.
Hang on tight; we're going to zip through this quickly and come back to the details in subsequent chapters. The first line in the program 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 the line:
End Module
Within the module definition, you write other programming constructs. For instance, you might define what is called an object. An object is an individual instance of a thing. Every object belongs to a more general category known as a class. While a class defines a type, each instance of that type is an object (much as Car defines a type of vehicle, and your aging rust-bucket is an individual instance of Car).
In VB.NET there are thousands of classes. Classes are used to define Windows controls (buttons, list boxes, etc.), as well as types of things (employees, students, telephones, etc.) in the program you are writing. Some classes you create yourself; some you obtain from the .NET Framework. Each class must be named. Classes are the core of VB.NET and object-oriented programming.
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: 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 that relates to your 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, 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 were 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 subatomic 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 place to place). 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. Every car will share certain characteristics (wheels, brake, accelerator, and so forth). 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 class. 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 also seeing 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 individual 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!
Defining a Class
When you define a class you describe the characteristics and behavior of objects of that type. In VB.NET, you describe characteristics with member fields, also known as properties.
Class Dog
   Private weight As Integer  ' weight is an integer
   Private name As String     ' the Dog's name as text
Member fields are used to hold each objects state. For example, the state of the Dog is defined by its current weight and name. The state of an Employee might be defined by (among other things) her current salary, management level, and performance rating. Chapter 8 includes a full discussion of member fields.
You define the behavior of your new type with methods. Methods contain code to perform an action.
Class Dog
   Private weight As Integer  ' weight is an integer
   Private name As String     ' the Dog's name as text
   Public Sub bark( )
                  'code here to bark
               End Sub
         
The keywords Public and Private are known as access modifiers, which are used to specify what classes can access particular members. For instance, public members can be called from methods in any class, while private members are visible only to the methods of the class that defines the member. Thus, objects of any class can call bark on a Dog, but only methods of Dog have access to the weight and name of the Dog. Access modifiers are discussed in Chapter 8.
A class typically defines a number of methods to do the work of that class. A Dog class might contain methods for barking, eating, napping, and so forth. An Employee class might contain methods for adjusting salary, submitting annual reviews, and evaluating performance objectives.
Methods can manipulate the state of the object by changing the values in member fields, or a method could interact with other objects of its own type or with objects of other types. This interaction among objects is crucial to object-oriented programming.
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, which has as one of its members an instance of Address.
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. 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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Encapsulation
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.
A class that provides a method that other classes can use is called a server. A class that uses that method is called a client. The goal of encapsulation is that you can change the details of how a server does its work without breaking anything in the implementation of the client.
This is accomplished by drawing a bright and shining line between the public interface of a class and its private implementation. The public interface is a contract issued by your class that says, I promise to be able to do this work. Specifically, you'll see that a public interface says call this method with these parameters, and I'll do this work and return this value. A client can rely on a public interface not to change. If the public interface does change, then the client must be recompiled and perhaps redesigned.
The private implementation, on the other hand, is, as its name implies, private to the server. The designer of the server class is free to change how it does the work promised in the public interface, so long as it continues to fulfill the terms of its implicit contract: it must take the given parameters, do the promised work and return the promised value.
For example, you might have a public method that promises as follows: Give me a dollar amount and a number of years, and I'll return the net present value. How you compute that amount is your business; if a client supplies a dollar amount and a number of years, you must return the net present value. You might implement that initially by keeping a table of values. You might change that at a later time to compute the value using the appropriate algebra. That is your business and does not affect the client. As long as you don't change the public interface (e.g., as long as you don't change the number or type of parameters expected or change the type of the return value,) your clients will not break while you change the implementation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Specialization
The second pillar, specialization, is implemented in VB.NET by declaring that a new class derives from an existing class. When you do so, the specialized class inherits the characteristics of the more general class. The specialized class is called a derived class, while the more general class is known as a base class.
The specialization relationship is referred to as the is-a relationship. A dog is a mammal, a car is a vehicle. (Dog would be derived from the base class Mammal, Car from the base class Vehicle.)
Specialization allows you to create a family of objects. In Windows a button is a control. A listbox is a control. Controls have certain characteristics (color, size, location) and certain abilities (can be drawn, can be selected). These characteristics and abilities are inherited by all of their derived types. This allows for a very powerful form of reuse. Rather than cutting and pasting code from one type to another, the shared fields and methods are inherited by the derived type. If you change how a shared ability is implemented, you do not have to update code in every derived type; they inherit the changes.
For example, a Manager is a special type of Employee. The Manager adds new capabilities (hiring, firing, rewarding, praising) and a new state (annual objectives, management level, etc.). The Manager, however, also inherits the characteristics and capabilities common to all Employees. Thus a Manager has an address, a name, an employee ID, and Managers can be given raises, can be laid off, and so forth. You'll see specialization at work in Chapter 11.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Polymorphism
Polymorphism , the third pillar of object-oriented programming, is closely related to inheritance. The prefix poly means many; morph means form. Thus, polymorphism refers to the ability of a single type or class to take many forms.
The essence of polymorphism is this: at times you will know you have a collection of a general type, for example a collection of Controls. You do not know (or care) what the specific subtype each of your controls is (one may be a button, another a listbox, etc.). The important thing is that you know they all inherit shared abilities (e.g., the draw method) and that you can treat them all as controls. If you write a programming instruction that tells each control to draw itself, this is implemented properly on a per-control basis (i.e., buttons draw as buttons, listboxes draw as listboxes, etc.). You do not need to know how each subtype accomplishes this; you only need to know that each type is defined to be able to draw.
Polymorphism allows you to treat a collection of disparate derived types (buttons, listboxes, etc.) as a group. You treat the general group of controls the same way, and each individual control does the right thing according to its specific type. Chapter 11 provides more concrete examples.
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 before programming anything, other than a trivial demonstration program, 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. 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 4: Visual Studio .NET
In Chapter 2 you learned that you can create your VB.NET applications using Notepad. In this chapter, you'll learn why you never will. Microsoft developed Visual Studio .NET (VS.NET) to facilitate the creation of Windows and web applications. You will find that this Integrated Development Environment (IDE) is a very powerful tool that will greatly simplify your work.
Visual Studio .NET offers many advantages to the .NET developer. The following features are discussed in this chapter:
  • A modern interface using a tabbed document metaphor for source code and layout screens, and toolbars and informational windows that dock where you want them.
  • Code completion, which enables you to enter code with fewer errors and much less typing.
  • IntelliSense, which pops up help on every method and function call as you type.
  • Dynamic, context-sensitive help, which allows you to view topics and samples relevant to the code you are writing at the moment.
  • Immediate flagging of syntax errors (e.g., missing characters, misplaced braces, etc.), which allows you to fix problems as they are entered.
  • The ability to compile and test programs right in the IDE.
  • A built-in task list to keep track of changes you need to make.
  • A Start Page that provides easy access to new and existing projects.
  • Customization capability, which allows you to set user preferences for IDE appearance and behavior.
One VS.NET feature will be so important to you, even as a VB.NET novice, that it actually merits its own chapter: An integrated debugger, which enables you to step through code, observe program runtime behavior, and set breakpoints, even across multiple languages. The debugger is considered in detail in Chapter 10.
In addition to these basic capabilities, VS.NET provides a number of advanced features that will simplify the development process. These features include:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Start Page
The Start Page is the first thing you see when you open Visual Studio .NET (unless you configure it otherwise). From here you can create new projects or open a project you worked on in a previous session. You can also find out what is new in .NET, access .NET newsgroups and web sites, search for help online, download useful code, or adjust Visual Studio .NET to your personal requirements. Figure 4-1 shows a typical Start Page.
Figure 4-1: Start Page
Along the top of the application window is a set of menus and buttons. These menus and buttons are context-sensitive (i.e., they will change as the current window changes).
Along the left side of the window is a series of links to other resources, such as new developments and events in the .NET community, the MSDN online library, and free sample applications.
A VB.NET program is built from source files, text files containing the code you write. Source code files are named with the .vb extension. The helloworld.vb file you created in Chapter 2 is a typical example.
A typical Visual Studio .NET application can have a number of other files (e.g., assembly information files, references, icons, data connections, etc.). VS.NET organizes these files into a container called a project.
Visual Studio .NET provides two types of containers for your source code, folders, files, and related material: the project and the solution. A project is a set of files that work together to create an executable program (.exe) or a dynamic link library (.dll ). Large, complex projects may consist of multiple .dll files called modules.
A solution is a set of one or more related projects. Each time you create a new project, Visual Studio .NET will either add it to an existing solution or create a new solution.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Inside the Integrated Development Environment (IDE)
The Visual Studio .NET IDE is centered around an editor. An editor is much like a word processor, except that it produces simple text (i.e., without formatting, such as bold, italics, etc.). As you may recall, source code files are simple text files.
The Visual Studio .NET IDE also provides support for building GUIs, which are integral to Windows and web projects. The following pages introduce some of the key features of the IDE.
The IDE is a Multiple Document Interface (MDI) application. There is a main window, and within the main window are a number of smaller windows. The central window is the text editing window. Figure 4-3 shows the basic layout.
Figure 4-3: The IDE
To the left of the editing window are a number of tabbed windows that contain tools used when creating Windows and web applications. To the right of the editing window is a window called the Solution Explorer. This window shows the files in the current project and the solution to which the project belongs.
In the lower-right corner is the dynamic help window. In the lower-left corner are a number of tabbed windows, including the task list. The IDE will add tasks to this list when your program has errors that must be fixed, and you can add tasks of your own to assist you in remembering what work remains to be done.
All of these windows are resizable and dockable, and many windows share space by using tabs. They can be resized by placing the mouse cursor over the edge you want to move. The cursor will change to a double arrow resizing cursor, at which point you can drag the window edge one way or the other.
The Visual Studio .NET window has a titlebar across the top, with menus below. Under the menus are toolbars with buttons that duplicate many of the common menu commands. Nearly everything that can be done through menus can also be done with context-sensitive pop-up menus, as described shortly.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
IntelliSense
Underlying the IDE is Microsoft's IntelliSense technology, which puts help and editing assistance (including code completion) instantly at your disposal. IntelliSense makes programmers' lives much easier. It provides real-time, context-sensitive help that appears right under your cursor.
For example, in the Hello World code shown in Chapter 2, you called the WriteLine( ) method for the Console object. If you write this code in VS.NET, the pop-up help will show you every available method of the Console object as soon as you type the dot (.), as shown in Figure 4-4. And if you begin to type a method—say you enter the letters "Wr"—IntelliSense jumps to the first method that matches what you've typed so far.
Figure 4-4: Pop-up code completion
Once you enter the method you want to call, Microsoft's pop-up help shows you the various versions of the method and helps you determine the parameters you'll need, as illustrated in Figure 4-5.
Figure 4-5: Pop-up help
Code completion automatically completes your thoughts for you, drastically reducing your typing. Drop-down lists provide all methods and properties possible in the current context, making them available at a keystroke or mouse click.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building and Running
You can run your application at any time by selecting either Start or Start Without Debugging from the Debug menu, or you can accomplish the same results by pressing either F5 or Ctrl+F5, respectively. You can also start the program by clicking the Start icon (pictured in Figure 4-6) on the Standard toolbar.
Figure 4-6: The Start icon
For console applications, the advantage of running the program with Ctrl+F5 is that Visual Studio .NET will open your application in a console window, display its results, and then add a line to press a key when you are ready, as shown in Figure 4-7. This keeps the window open until you've seen the results and pressed a key, at which point the window will close.
Figure 4-7: Running the application
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
For More Information
This brief overview of Visual Studio .NET was intended to familiarize you with the tool. There is a great deal more to know about this tool, but most of it will not be relevant to creating the simple applications in this book.
The best way to learn about the power and scope of Visual Studio .NET is to use it and to explore its various nooks and crannies. Try right-clicking in various places and explore the context-sensitive pop-up menus as well.
As you make your way through the book, you'll see various helpful features of Visual Studio .NET highlighted. All of these tips should make programming in VB.NET easier for you. The application's online help files (MSDN) provide extensive additional support.
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: VB.NET Language Fundamentals
Chapter 2 demonstrates a very simple VB.NET program that prints the text string "H