BUY THIS BOOK
Add to Cart

Print Book $49.99


Add to Cart

Print+PDF $64.99

Add to Cart

PDF $39.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £35.50

What is this?

Looking to Reprint or License this content?


Visual Basic 2005 in a Nutshell
Visual Basic 2005 in a Nutshell, Third Edition By Tim Patrick, Steven Roman, Ph.D., Ron Petrusha, Paul Lomax
January 2006
Pages: 766

Cover | Table of Contents


Table of Contents

Chapter 1: Introduction
Since its introduction in 1991, Microsoft Visual Basic has enjoyed unprecedented success. In fact, in slightly more than a decade, it has become one of the world's most widely used programming languages, with millions of productive developers using various flavors of the language.
The reason for this success is twofold. First, Visual Basic has excelled as a rapid application development (RAD) environment for corporate and commercial applications. Second, Visual Basic offers a programming language and development environment noted for its simplicity and ease of use, making it an extremely attractive choice for those new to programming.
With the introduction of the .NET platform, Microsoft also released a new version of the Visual Basic language, Visual Basic .NET. VB.NET is a from-the-ground-up rewrite of Visual Basic that not only adds a number of new features but also differs significantly from previous versions of Visual Basic. From a high-level view, two of these differences are especially noteworthy:
  • Until the release of .NET, Microsoft focused on creating a unified version of Visual Basic for Applications (VBA), the language engine used in Visual Basic, which could serve as a "universal batch language" for Windows and Windows applications. With Version 6 of Visual Basic, this goal was largely successful: VB 6.0 featured VBA 6.0, the same language engine that provided macro language functionality to the Microsoft Office suite, Microsoft Project, Microsoft FrontPage, Microsoft Visio, and a host of popular third-party applications such as AutoDesk's AutoCAD and Corel's WordPerfect Office suite. With the release of .NET, this emphasis on a unified programming language has, for the moment at least, faded into the background; .NET did not become the macro language platform for Microsoft Office or other applications. (That may change over time; SQL Server 2005, for instance, provides significant support for stored procedure scripting using .NET languages.)
  • Since Version 4, Visual Basic had increasingly been used with COM and ActiveX. The development of ActiveX components was generally straightforward in VB, and the language could also take advantage of an increasing number of Microsoft-supplied and third-party ActiveX components, including ActiveX Data Objects (ADO), Collaborative Data Objects (CDO), and the Outlook object model. Although .NET supports COM for reasons of backward compatibility, it is designed primarily to work with .NET Framework-generated components rather than with COM.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Visual Basic .NET?
When Visual Basic was introduced in 1991, Windows 3.0 was a fairly new operating system in need of application and utility software. Although Windows 3.0 itself had proven successful, the graphical applications that offered native support for Windows—and upon the release of which the ultimate success or failure of Windows would depend—were slow in coming. The major problem was that C and C++ programmers, who had produced the majority of applications for the MS-DOS operating system, were faced with a substantial learning curve in writing Windows applications and adapting to Windows' event-driven programming model.
The introduction of Visual Basic immediately addressed this problem by offering a programming model that was thoroughly consistent with Windows' graphical nature. Although Windows marked a radical change in the way programs were written, C and C++ programmers continued to produce code as they always had: a text editor was used to write source code, the source code was compiled into an executable, and the executable was finally run under Windows. Visual Basic programmers, on the other hand, worked in a programming environment that its critics derisively labeled a "drawing program." Visual Basic automatically created a form (or window) whenever the developer began a new project. The developer would then "draw" the user interface by dragging and dropping controls from a toolbox onto the form. Finally, the developer would write code snippets that responded to particular events, such as the window being resized or a button control being clicked. Visual Basic's initial success was due to its ease of use, especially the simplicity of its graphical programming environment that was entirely consistent with the graphical character of Windows itself.
To get some sense of the revolutionary character of Visual Basic, it is instructive to compare a simple "Hello World" program for Windows 3.0 written in C (see Example 1-1) with one written in pre-.NET Visual Basic (see Example 1-2). While the former program is over two pages long, its Visual Basic counterpart takes only three lines of code—and two of them are provided automatically by the Visual Basic environment.
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 Is Visual Basic .NET?
Visual Basic .NET is a programming language designed to create applications that work with Microsoft's .NET Framework. The .NET platform, in turn, addresses many of the limitations of "classic" COM, Microsoft's Component Object Model, which provided one approach toward application and component interoperability. These limitations included type incompatibilities when calling COM components, versioning difficulties when developing and installing new versions of COM components (known as "DLL hell"), and the need for developers to write a certain amount of code (mostly in C++) to handle the COM "plumbing." In contrast to pre-.NET VB, with its reliance on COM, Visual Basic as a .NET language offers a number of new features and advantages. Let's take a look at some of these.
With the release of Version 4, Visual Basic added support for classes and class modules and, in the process, became an object-oriented programming (OOP) language. Yet the debate persists about whether pre-.NET Visual Basic was a "true" object-oriented language, or whether it only supported limited features of object orientation. Detractors point out that Visual Basic did not support inheritance of a base class's functionality, only of its interface or signature. While Visual Basic still had a solid base of object-oriented features, purists emphasized the very real limitations in VB's OOP implementation.
While the object-oriented character of previous versions of VB may be in doubt, there is no question that .NET is an object-oriented programming platform. In fact, even if Visual Basic .NET is used to write what appears to be procedural code, it is object-oriented "under the hood." As an example, consider the clearly procedural, non-object-oriented program shown in Example 1-3.
Example 1-3. A procedural program in .NET
Module Module1
   Public Sub Main()
      Dim x As Integer
      x = 10
      MsgBox(Increment(x))
   End Sub

   Private Function Increment(ByVal baseValue As Integer) As Integer
      Return baseValue + 1
   End Function
End Module
If you use ILDASM (.NET's equivalent of a disassembler) to look at the IL ("Intermediate Language," somewhat similar to assembly language in the non-.NET world) generated for this source code (see Figure 1-1), you see that internally,
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 Can You Do with Visual Basic .NET?
With its language enhancements and its tight integration into the .NET Framework, Visual Basic is a thoroughly modernized language that has become one of the premier development tools for creating a wide range of .NET applications. In the past, Visual Basic was often seen as a "lightweight" language that could be used for particular kinds of tasks but was wholly unsuited for others. (It was often argued, sometimes incorrectly, that you couldn't create such things as Windows dynamic link libraries or shell extensions using Visual Basic.) In the .NET Framework, Visual Basic emerges as an equal player; Microsoft's claim of language independence—that programming language should be a lifestyle choice, rather than something forced on the developer by the character of a project—is realized in the .NET platform.
This means that Visual Basic can be used to create a wide range of applications and components, including the following:
  • Standard Windows applications
  • Windows console mode applications
  • Windows services
  • Windows controls and Windows control libraries
  • Web (ASP.NET) applications
  • XML Web services
  • Web controls and web control libraries
  • .NET classes and namespaces
  • Applications that interact with legacy COM components
Most importantly, with the release of .NET, Visual Basic becomes an all-purpose development environment for building Internet applications, an area in which it has traditionally been weak. Each successive release of Visual Basic should further enhance its position as the tool of choice for developing state-of-the-art software, both now and long into the future.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Versions of Visual Basic for .NET
.NET brought about a major progression in the Visual Basic language, but it wasn't a once-and-for-all change. Since VB's initial .NET release in 2002, it and the underlying .NET Framework have been updated several times to include new functionality. As of this writing, there have been three major releases of Visual Basic.
  • Visual Basic .NET 2002. This was the original release of Visual Basic .NET and was packaged with Version 1.0 of the .NET Framework. Internally, this release is known as Visual Basic 7.0. For a list of changes between Visual Basic 6.0 and the 2002 release of VB.NET, see Appendix D.
  • Visual Basic .NET 2003. The second release of Visual Basic was a "minor" release, with limited functionality changes. It shipped with Version 1.1 of the .NET Framework and was identified internally as Visual Basic 7.1. For a list of changes between the 2002 and 2003 releases of VB.NET, see Appendix E.
  • Visual Basic 2005. The third and most recent release of Visual Basic is a "major" update to the language. Internally, it is known as Visual Basic 8.0, and it comes with a parallel update to the .NET Framework, Version 2.0. For a list of changes between the 2003 and 2005 releases of VB, see Appendix F.
When .NET first appeared, it significantly raised the learning curve for first-time developers looking to try out Visual Basic. It was designed as a professional tool for professional programmers. The 2005 release of Visual Basic attempts to bring new programmers back into the Visual Basic world by expanding the usability range of the product line. Visual Studio 2005 includes several distinct audience-targeted packages.
  • Visual Studio 2005 Express Edition. This is the entry-level product, and it is available as a more specific Visual Basic 2005 Express Edition. (Actually, each .NET language is a separate product in the Express Edition line.) This package includes a simplified development environment interface, some restrictions on functionality (at least through the development environment), and features that help first-time developers become more productive in Visual Basic. A companion product (though included in Visual Studio 2005 Express Edition) is Visual Web Developer 2005 Express Edition, a simpler and more lightweight web application development tool. Express Edition users who want to develop web applications must install Visual Web Developer.
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: The .NET Framework: General Concepts
This chapter provides a high-level overview of the most important .NET Framework concepts. There are many concepts that are new and different from Visual Basic's pre-.NET days, but some of them are quite technical or esoteric and are beyond the scope of this book. The discussion here is limited to those essential features that you must know to program effectively using .NET. For a more thorough coverage of .NET concepts, see Thuan Thai and Hoang Q. Lam's book, .NET Framework Essentials (O'Reilly).
The Common Language Runtime (CLR) is an environment that manages code execution and provides application-development services. It provides all of the common features required by all .NET-enabled languages. Visual Basic and other .NET languages are simply wrappers that expose the CLR's functionality. Because the CLR provides all of the core functionality for all .NET languages, components written in different .NET languages can interact with each other immediately, with no language-specific conflicts. Even data types are shared among .NET languages through the CLR's Common Type System (CTS). While data types may have different names in Visual Basic than they do in C#, they will all be based on underlying CLR data types.
The Common Language Specification (CLS) defines the minimal set of .NET features that must be implemented by a .NET-compliant compiler. Components developed to be CLS-compliant may be limited in their ability to interact with applications and components that use a wider range of .NET features.
The output of a .NET compiler includes metadata, which is information that describes the objects that are part of the generated application or library. The metadata describes the following:
  • Data types and their dependencies
  • Objects and their members
  • References to required components
  • Information (including versioning information) about components and resources that were used to build the application or library
Metadata is used by the CLR to support functionality such as:
  • Manage memory allocations
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Common Language Runtime
The Common Language Runtime (CLR) is an environment that manages code execution and provides application-development services. It provides all of the common features required by all .NET-enabled languages. Visual Basic and other .NET languages are simply wrappers that expose the CLR's functionality. Because the CLR provides all of the core functionality for all .NET languages, components written in different .NET languages can interact with each other immediately, with no language-specific conflicts. Even data types are shared among .NET languages through the CLR's Common Type System (CTS). While data types may have different names in Visual Basic than they do in C#, they will all be based on underlying CLR data types.
The Common Language Specification (CLS) defines the minimal set of .NET features that must be implemented by a .NET-compliant compiler. Components developed to be CLS-compliant may be limited in their ability to interact with applications and components that use a wider range of .NET features.
The output of a .NET compiler includes metadata, which is information that describes the objects that are part of the generated application or library. The metadata describes the following:
  • Data types and their dependencies
  • Objects and their members
  • References to required components
  • Information (including versioning information) about components and resources that were used to build the application or library
Metadata is used by the CLR to support functionality such as:
  • Manage memory allocations
  • Locate and load class instances
  • Manage object references and perform garbage collection
  • Resolve method invocations
  • Generate native code
  • Make sure that the application has the correct versions of necessary components and resources
  • Enforce security
By including metadata in a compiled software component, that component becomes "self-describing." This tells the CLR everything it needs to prepare and execute a .NET application, and to allow it to interact with other .NET 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!
Managed Code
Code created within the CLR environment is called managed code . Applications and libraries created using non-.NET tools, such as VB 6 applications, and COM and ActiveX components, are not managed code. You can still use unmanaged components in your .NET applications, but they must be referenced through special "interop" conduits to prevent the unmanaged code from having any detrimental impact on the managed side of the application.
Having a central manager of all things .NET like the CLR makes possible some nice centralized functionality. One such feature in .NET is the garbage collection system, which automatically disposes of all variables and data objects when an application is finished with them, reclaiming every byte and releasing all references to the related memory.
Managed execution is the process of running your .NET applications in the context of the CLR, although this process officially starts when writing your first line of .NET source code. There are three simple steps to managed execution .
  1. Write code using one or more .NET compilers. Some compilers (like the C++ compiler for .NET) can generate code that is unmanaged or that falls outside the official CLS. Such code cannot easily interact with components from other .NET languages, so avoid it in mixed-language applications.
  2. Compile the code. The compiler translates source code to Intermediate Language code (IL), also called Microsoft Intermediate Language (MSIL) or Common Intermediate Language (CIL), and generates the necessary metadata for the application.
  3. Run the code. When .NET code is executed, the IL is compiled into CPU-specific native code by a Just In Time (JIT) compiler. The resulting application is run within the context of the CLR.
One benefit of running applications within the CLR-managed environment is that data within the application is kept safe. The CLR keeps errant code and malformed data from interfering with the rest of memory, either in your application or elsewhere in the system.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Namespaces
The notion of a namespace plays a fundamental role in the .NET Framework. In general, a namespace is a logical grouping of types (classes and similar constructs) for the purposes of identification and navigation. There are so many classes and features in .NET that there are bound to be name conflicts. And since third-party libraries can be integrated into the class space just like the Microsoft-supplied libraries, namespaces keep everything neat and orderly.
Imagine that, in a certain business, there is an executive named John Smith, a secretary named John Smith, and a custodian named John Smith. In this case, the name John Smith is ambiguous. When the paymaster stands on a table and calls out the names of people to receive their paychecks, the executive John Smith won't be happy if he rushes to the table when custodian John Smith's paycheck is in the paymaster's hand.
To resolve the naming ambiguity, the business can define three namespaces: Executive, Secretarial, and Custodial. Now the three individuals can be unambiguously referred to by their fully qualified names:
  • Executive.John Smith
  • Secretarial.John Smith
  • Custodial.John Smith
Namespaces in .NET look a lot like these references to John Smith. They are simply names used to group and organize all of the .NET classes into a hierarchy. Namespaces can be nested. Consider the following three possible namespaces.
  • America Namespace
  • America.Washington Namespace
  • America.Washington.Seattle Namespace
Each of these namespaces can include classes (and other types) and additional namespaces. And the same class name can appear in multiple namespaces, even in nested namespaces.
  • America.Demographics Class
  • America.Washington.Demographics Class
  • America.Washington.Seattle.Demographics Class
  • America.Montana.Demographics Class
The .NET Framework Class Library (FCL) consists of several thousand classes and other types (such as interfaces, structures, and enumerations) that are divided into about 200 namespaces. All classes considered to be the "core" language-neutral classes of .NET appear in the System namespace, or in one of the nested namespaces within
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Types and Objects
Pretty much everything in a .NET application is contained in a type. Types include:
  • Classes, which are basically collections of data values, and the related code that manages that data. Usually a class has both data and code, but a particular class might just have either data or code. In Visual Basic, a Module is a variation of a class.
  • Interfaces, which are class "skeletons." Interfaces define the basic structure of a class but without the actual implementation. They are useful for defining a common layout of features to be shared by many related classes.
  • Delegates, which .NET uses to implement its event-driven infrastructure.
  • Enumerations, which are collections of named numeric elements.
  • Value types and reference types. Normally, when you create an object (an in-memory instance of a class), that object sits in memory somewhere, and your object variable contains the memory location of the object block. (It's like a pointer, for those familiar with the C language parlance.) These are reference types. The .NET type system also supports value types. A value type variable stores the actual data value instead of a memory address to the true location of the data.
  • Other similar things. You can subdivide the type system forever, but everything is eventually called a type.
From the Visual Basic point of view, all types are really classes. Of course, all data objects are instances of classes, but even your source code—even your Sub Main routine—is part of a class, and it must be part of a class to be part of a .NET application.
Classes define a chunk of related data and functionality. When you design a class, you are saying, "I'm planning on creating an object that has these features and that stores this type of data and information." Objects are the actual in-memory instances of a class. For a much richer description of objects and other object-oriented concepts, see Chapter 3.
The root of the type hierarchy is the System.Object class. All new classes you design eventually tie back to the System.Object class. This class provides some basic functionality required of all classes and provides a convenient way to generically identify any object in your 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!
Assemblies
An assembly is a single .NET executable (EXE file) or library (DLL file). Since these file types existed before .NET was invented, why bother to give them a special name? Well, it's not just the type of file; it's what is in the file that counts. (By the way, a .NET purist will insist that a single assembly can be split into multiple files. While this is true, it rarely happens, especially since it can't be done from within the Visual Studio development environment.)
An assembly is a unit of deployment; that is, it's a file that can be deployed on a user's system. .NET applications are made up of one or more assemblies , all working together for a common goal. Inside of an assembly, you find the following:
  • The executable code of your application. Generally you will have a single primary EXE assembly, plus optional DLL assemblies.
  • Embedded data, such as resources (graphics, strings, etc.).
  • .NET-specific security permissions required for the assembly.
  • The types (classes and so on) used in the assembly, including public classes that can be accessed by other assemblies (applications).
  • Listings of the external types and references needed by the assembly, including references to other assemblies. These references also indicate the specific or minimum version number expected for those external components.
  • Version information for the assembly. Assemblies include a four-part version number (major, minor, revision, and build, as in "2.1.0.25"), and this version number determines how the assembly interacts with other assemblies and components. .NET allows you to install different versions of an assembly on a single machine and have specific versions accessed by other applications. For instance, you may have Versions 1.0 and 2.0 of a spellchecking component installed on a workstation, one for an old word processor (that requires Version 1.0) and one for a newer email system (that uses Version 2.0). Both versions can reside on the same system without conflict. In fact, both versions can be actively running at the same time, a feature known as side-by-side execution.
Much of this information is stored in the assembly's metadata, which was discussed earlier. As a unit, this metadata is known as the assembly's
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 Framework Class Library
Although .NET itself is very powerful and very cool, it doesn't provide much in the way of specific functionality. The .NET Framework provides a generic system for application development, but it's really all plumbing. It's not that different from the old-style C++ or Pascal compilers. If you want to sort a list of strings in reverse order by length, draw a line on the screen, interact with a database, or send a data packet across the Internet, you still have to write all of that functionality yourself. Or do you?
Fortunately, you don't have to do it all by yourself. The .NET Framework includes a library of prewritten features that provide a lot of the functionality you really wanted, but that you didn't want to write yourself. This library uses a layered approach. At the bottom of the library is the Base Class Library (BCL), which defines the central and common features that every .NET language will use, such as:
  • Implementation of all core data types
  • Data structures, such as stacks, queues, and collections
  • Diagnostic and tracking features
  • Basic input and output with various sources, such as files and serial ports
On top of this foundation you find the FCL, which is pretty much everything else that Microsoft thought programmers (including programmers designing the .NET system) would find useful. Among the many library classes are:
  • XML manipulation tools
  • ADO.NET, a collection of generic and platform-specific database interaction components
  • GDI+, the core drawing system for on-screen and printed output
  • Windows Forms, a package for creating desktop applications
  • ASP.NET, a web-based programming system
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application Deployment
Once you write your VB application, you still have to install it on each user's system. .NET provides two deployment methods. The first method, Windows Installer deployment, was actually around for a while before the first release of the .NET Framework. Windows Installer deployments are basic Setup packages that the user installs from a single ".msi" file. All releases of .NET-centric Visual Basic (except for some of the more entry-level 2005 editions) allow you to create a deployment project, the output of which is an ".msi" file packed with all the files needed to install your application. Since the basic installer project features in Visual Studio include limited support for custom installation scenarios, several third-party vendors provide enhanced products for generating more advanced Windows Installer files.
New in 2005. The .NET Framework, Version 2.0, part of the 2005 release of Visual Studio, includes a new deployment method called ClickOnce. Because Windows Installer deployments often update important system files or registry entries, the user installing the package usually needs to be a local administrator on the workstation to complete the installation. ClickOnce deployments get around this by installing the application in its own protected environment (that is, the rest of the workstation is protected from it!). ClickOnce-installed applications are convenient for users; they are designed for easy single-click installation from a web site, and they can be configured to automatically check for and install updated versions.
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 and Visual Basic
Visual Basic, as a .NET language, uses all of the core features of the Common Language Runtime, the Common Type System, namespaces, assemblies, types, and all other .NET elements, packaging them up in a nice, neat programming system.
To write a Visual Basic application, you create classes that implement your desired functionality and data manipulation features. All application data is stored in memory using the Common Type System data types that Visual Basic uses for its own basic data types. The application manipulates this data using many of the prewritten classes in the Framework Class Library. All of this code gets organized into namespaces of your choosing and is compiled into one or more assemblies. Your application is now ready to deploy and run.
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: Introduction to Object-Oriented Programming
Before you can write quality Visual Basic applications on the .NET platform, you must have a good understanding of objected-oriented programming (OOP) concepts. This chapter presents a brief introduction to these concepts.
Visual Basic has included at least some object-oriented programming features since Version 4. But these features were limited, and some workarounds were required to simulate the missing features, if they could be simulated at all. The advent of .NET infused Visual Basic with a more complete set of OOP features.
You may be saying to yourself: "I prefer not to use object-oriented techniques in my programming." Unfortunately, this is not an option in the .NET flavor of Visual Basic. Every line of code, apart from a few statements that appear in the declarations section of each code file, appears within a class—one of the core building blocks of object-oriented software development. Also, all features contained within the Framework Class Library are built on object-oriented principles.
Object-oriented programming is a software development architecture that uses the object—a "black box" of data and related functionality—as its focus. These objects are built on four main facets of OOP design: abstraction, encapsulation, inheritance, and polymorphism. This section introduces each of these concepts and also the notion of an interface as the means of interaction with the contents of an object's black box.
An object is a software-based collection of data elements and related procedures that act on those data elements. Obviously, objects are the central theme of "object-oriented" programming. In Visual Basic and other similar OOP languages, a class is the source code design of an object. An object is an in-memory instance of a class in a running program. Multiple object instances based on a single class can exist in memory at the same time.
Although the terms "class" and "object" have distinct meanings, the terms are used somewhat interchangeably in this chapter, at least in those cases where the distinction is not necessarily important.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Principles of Object-Oriented Programming
Object-oriented programming is a software development architecture that uses the object—a "black box" of data and related functionality—as its focus. These objects are built on four main facets of OOP design: abstraction, encapsulation, inheritance, and polymorphism. This section introduces each of these concepts and also the notion of an interface as the means of interaction with the contents of an object's black box.
An object is a software-based collection of data elements and related procedures that act on those data elements. Obviously, objects are the central theme of "object-oriented" programming. In Visual Basic and other similar OOP languages, a class is the source code design of an object. An object is an in-memory instance of a class in a running program. Multiple object instances based on a single class can exist in memory at the same time.
Although the terms "class" and "object" have distinct meanings, the terms are used somewhat interchangeably in this chapter, at least in those cases where the distinction is not necessarily important.
An abstraction is a view of an entity that includes only those aspects that are relevant for a particular situation. It takes something from the real world—an employee, a book, a chart of accounts, a galaxy, a grain of sand—and breaks it down into individual elements that can be managed with software. Consider a software component that provides services for tracking an employee's information. The first step in designing such a component is to identify the items or features that would be managed by the component. Some of these items may be:
  • Employee full name
  • Employee home address
  • Company ID for the employee
  • Current salary
  • Length of employment
  • Features to adjust the salary based on a rule
This list includes not only basic data values, or properties , but also common actions to be taken on the data, or methods . Properties of the class, such as the employee's full name, are sometimes called fields, and they may have limits on the type or range of data allowed. Methods may require additional information (such as a table of salary adjustment rules for the salary adjustment feature) to work properly. These actions are sometimes referred to as operations or behaviors. Together, the properties and methods are known as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
OOP Development in Visual Basic
The .NET Framework is an OOP-rich development environment. Within that environment, Visual Basic provides access to most OOP features.
The primary OOP entity in Visual Basic is the class, but the language also supports two additional variations of this standard entity: (1) the structure, a value-type variation (always derived from System.ValueType) of the normally reference-type class, and (2) modules, a class in which all members are shared and public by default. These three primary development entities, along with a few other entities, such as enumerations, fall under the broad name of type in .NET parlance. Unless otherwise noted, all discussions of class features apply also to structures and modules.
Most Visual Basic development establishes a one-to-one relationship between a class and a source code file. However, a single file may include multiple classes . Beginning in 2005, the code for a single class may also be split among multiple source code files by using the new Partial keyword. See the entry for that keyword in Chapter 12 for additional information on its usage.
The basic source code needed to define a class is pretty simple.
Public ClassclassName

End Class
Once a class is defined, it can be used by creating an instance of the class, which is what is really known as the object. (Some class members can be used without creating an instance; these "shared members" are discussed below.) Instantiating an object requires (1) a variable to hold the object and (2) the creation of the object using the New keyword. These two steps are often performed in two separate VB statements.
Dim myInstance As SimpleClass  ' Defines the variable
myInstance = New SimpleClass   ' Creates the object
These two steps can be combined into a single statement:
Dim myInstance As SimpleClass = New SimpleClass
A shortcut syntax makes the instantiation even simpler:
Dim myInstance As New SimpleClass
Visual Basic classes contain the following types of members:
Field Members
This includes member variables and constants. Enumerated data types defined within a class fall into this category.
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: Variables and Data Types
Data manipulation is the heart of any software application. You could choose to process the data the way that your computer's CPU does: bit by bit. But that quickly becomes tedious, so languages like Visual Basic include a variety of data types , implementations of data management tools each based on a subset of possible data values. This chapter discusses data types, the data managed by those types, and how they are processed in Visual Basic and .NET.
The term "data types" differs from the more general term "types" used throughout this and other .NET documentation. .NET is built on the concept of the type, the basic data construct of .NET, which includes classes, structures, delegates, and other high-level elements used to build applications and pass data around programs. The data types available in .NET are built from these more generalized types, as are your own custom classes. Data types provide a small but essential set of data manipulation tools, grouped by the subset of possible data values managed by each data type.
The .NET Common Language Runtime (CLR) includes the Common Type System (CTS ), which defines the data types that are supported by the CLR. Each .NET-enabled language implements a subset of the CLR data types, although some languages implement all of them (Visual Basic does, starting in 2005).
In .NET, data types are special classes and structures whose instances manipulate a data value that must fall within the limited range of the data type. For instance, the Byte data type can support and manage any 8-bit unsigned integer value, from 0 to 255. It allows no other data values outside of this defined subset, but it handles this subset extremely well. .NET provides data types for those subsets of data that programmers have found essential in software development. These data types make it possible to manipulate virtually any variation of data. For those instances where a predefined .NET data type will not meet your needs, you can use the predefined data types as building blocks to develop your own custom data management 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!
Data Types
The .NET Common Language Runtime (CLR) includes the Common Type System (CTS ), which defines the data types that are supported by the CLR. Each .NET-enabled language implements a subset of the CLR data types, although some languages implement all of them (Visual Basic does, starting in 2005).
In .NET, data types are special classes and structures whose instances manipulate a data value that must fall within the limited range of the data type. For instance, the Byte data type can support and manage any 8-bit unsigned integer value, from 0 to 255. It allows no other data values outside of this defined subset, but it handles this subset extremely well. .NET provides data types for those subsets of data that programmers have found essential in software development. These data types make it possible to manipulate virtually any variation of data. For those instances where a predefined .NET data type will not meet your needs, you can use the predefined data types as building blocks to develop your own custom data management class.
The .NET Framework implements nearly 20 of these essential core data types, most designed to manipulate integer or floating point numbers. The native VB data types are wrappers for the core data types. For instance, the VB Integer data type is a wrapper for the System.Int32 structure. One of the members of the Int32 structure is MaxValue, which returns the maximum numeric value allowed for this data type. Thus, even though MaxValue is not officially part of VB, the Integer data type's full dependence on the Int32 data type allows the following usage:
    Dim usesInt32 As Integer
    MsgBox(usesInt32.MaxValue)   ' Displays 2147483647
Before the 2005 release of .NET, only some of the core .NET data types were implemented in Visual Basic. Yet even without specific VB wrappers, the earlier releases of VB.NET still provided access to the unwrapped data types. Since the core data types are simply classes and structures, they can be instantiated just like any other class or structure.
Data types in Visual Basic fall into two broad categories: (1)
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
A variable can be defined as an entity that has the following six properties:
Name
A variable's name is used to identify it in code. In VB, a variable name starts with a Unicode alphabetic character or an underscore and is then followed by additional underscore characters or various Unicode characters, such as alphabetic, numeric, formatting, or combined characters. With the introduction of .NET, Microsoft recommends a new set of naming standards for use with variables and other named objects. These naming standards are discussed briefly in the "Naming Conventions" section of Chapter 1.
Address
Every variable has an associated memory address, the location where the variable's value is stored. Variables are not guaranteed to maintain a permanent memory address in .NET, so the address of a variable should not be recorded or used.
Data Type
The data type of a variable determines the possible values that the variable can assume.
Value
The value of a variable is the data content it contains at its memory address. This is also sometimes referred to as the r-value of the variable, since it is what appears on the right side of a variable assignment statement. For instance, in the code:
    Dim targetValue As Integer = 5
the statement can be read as "store the value of 5 in memory at the address of targetValue." Because it appears on the left side of an assignment operator, the variable (or its memory location) is sometimes called an l-value.
Scope
The scope of a variable determines where in a program that variable is visible to the code. Variable scope is discussed in more detail later in this chapter.
Lifetime
A variable's lifetime determines when and for how long a particular variable exists. It may or may not be visible (that is, be in scope) for that entire period. Variable lifetime is described in more detail later in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constants
Constants are essentially read-only variables. Once their value is set in code (at compile time), they cannot change. Constants are defined at the local or module level using the Const keyword:
accessModifier Const name As type = value
where accessModifier is one of the access modifiers defined earlier. (Access modifiers are not used for constants declared in procedures.) When Option Strict is On, all constant declarations must have a declared type.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enumerations
An enumeration appears as a group of related integer constants. All members of an enumeration share the same data type, and it must be an integral data type (Byte, Integer, Long, or Short, and also—in 2005 or beyond—SByte, UInteger, ULong, or UShort). The enumeration members are shared and read-only for the lifetime of the application.
    Public Enum VehicleType As Integer
       bicycle = 2
       tricycle = 3
       passengerCar = 4
       eighteenWheeler = 18
    End Enum
They are used in code just like constants or variables.
    Dim whatIDrive As VehicleType
    whatIDrive = VehicleType.passengerCar
Enumerations are declared at the namespace or module level only; you cannot define an enumeration within a procedure.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arrays
The array is a fundamental data structure in many programming languages, including Visual Basic. Arrays store a collection of similar data types or objects. Each element has a numbered position, ranging from 0 (the lower bound) to the defined upper bound of the array.
The following examples show various ways to declare a one-dimensional array:
    ' Implicit constructor: No initial size and no initialization
    Dim days(  ) As Integer

    ' Explicit constructor: No initial size and no initialization
    Dim days(  ) As Integer = New Integer(  ) {}

    ' Implicit constructor: Initial size but no initialization
    Dim days(6) As Integer

    ' Explicit constructor: Initial size but no initialization
    Dim days(  ) As Integer = New Integer(6) {}

    ' Implicit constructor: Initial size implied by initialization
    Dim days(  ) As Integer = {1, 2, 3, 4, 5, 6, 7}

    ' Explicit constructor, Initial size and initialization
    Dim days(  ) As Integer = New Integer(6) {1, 2, 3, 4, 5, 6, 7}
Array declarations can:
  • Call the array's constructor implicitly or explicitly
  • Specify an initial size for each dimension or leave the initial size unspecified
  • Initialize the elements of the array or not
In VB 6, the programmer could specify both the lower and upper bounds of any array dimension. With .NET, all Visual Basic arrays have a lower bound of zero. The statement:
    Dim myArray(5) As Integer
declares an array with six elements, numbered zero through five.
Arrays can include multiple dimensions. The following example declares and initializes a two-dimensional array:
    Dim rectArray(,) As Integer = {{1, 2, 3}, {4, 5, 6}}
The following code displays the contents of this array:
    Debug.Write(rectArray(0, 0))
    Debug.Write(rectArray(0, 1))
    Debug.WriteLine(rectArray(0, 2))
    Debug.Write(rectArray(1, 0))
    Debug.Write(rectArray(1, 1))
    Debug.WriteLine(rectArray(1, 2))

    ' ----- The output is:
    123
    456
The upper bound of any array dimension can be modified using the ReDim statement.
    ReDim [Preserve]arrayName(newUpperBound)
The Preserve qualifier retains any existing values in the array; all array elements are cleared in the absence of this qualifier. When using
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Collections
Visual Basic defines an associative array object called a collection. Although similar to an array in that elements appear in a specific order, a collection stores its elements as key-value pairs. Once in a collection, each element can be retrieved by position, by key, or by iterating through the collection one element at a time.
Five of the Collection class's members are especially useful.
Add Method
Adds an item to the collection. Along with the data itself, you can specify an optional key by which the member can be referenced.
Clear Method
Removes all elements from the collection.
Count Property
Returns the number of elements in the collection.
Item Property
Retrieves an element from the collection either by its index (or ordinal position in the collection) or by its key (if provided when the element was added).
Remove Method
Deletes an element from the collection using the element's index or key.
The following code defines a collection of state names, using the state abbreviation as the key.
    Dim states As New Collection
    states.Add("New York", "NY")
    states.Add("Michigan", "MI")
The elements of this collection can then be iterated using the For Each...Next construct.
    Dim oneState As String
    For Each oneState In states
       MsgBox(oneState)
    Next oneState
Like arrays, collection members are accessible by their index value. The lower bound of a collection is always one (1).
New in 2005. The 2005 release of Visual Basic includes a new generics feature that allows collection (and other class) instances to be tied to a specific data type. See Chapter 10 for details on using this new feature.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Parameters and Arguments
Although procedures are self-contained blocks of code, they often need to interact with data from outside of the procedure. External data can be passed into the procedure through its parameter list. This list appears immediately on the declaration line of the procedure itself.
    Public Function RepeatString(ByVal origText As String, _
          ByVal howManyTimes As Integer) As String
       ' ----- Return a string concatenated to itself many times.
       Dim counter As Integer
       RepeatString = ""
       For counter = 1 To howManyTimes
          RepeatString &= origText
       Next counter
    End Function
The RepeatString function includes two parameters, origText and howManyTimes. Each parameter includes a data type and a passing method. The passing method is either ByVal ("by value") or ByRef ("by reference"). In .NET, the default parameter passing method is ByVal.
When calling a procedure that has parameters, the values you send from the initiating code are called arguments. The following statement includes two arguments in the call to the RepeatString function: a string ("abc") and an integer (5).
    targetString = RepeatString("abc", 5)
Because classes in .NET support overloaded methods, the arguments you send to a procedure must match the parameter signature of one of the overloaded methods. See Chapter 3 for a broader discussion of overloading.
All arguments are passed by value or by reference, depending on whether the ByVal or ByRef keyword is used with a parameter. When data is passed by value, a copy of the source expression or variable is sent to the target procedure. While in that procedure, the parameter acts just like a local variable; it can be examined and modified within the procedure, and it disappears when the procedure is finished. Any changes made to a ByVal parameter in the procedure are not reflected in the source variable. This is clearest when working with value types. Consider the following code.
    Public Sub ParentRoutine(  )
       Dim sourceValue As Integer = 5
       ChildRoutine(sourceValue)
       MsgBox(sourceValue)   ' --> Displays "5"
    End Sub

    Public Sub ChildRoutine(
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: Operators
Operators are the basic data manipulation tools of any programming language. All data ultimately breaks down into single bits of 0 and 1. And the whole reason a computer exists is to manipulate those single bits of data with basic operators. This chapter discusses the basic operators available in Visual Basic, and how they interact with data.
Operators come in two usage types: unary and binary. Unary operators work on a single operand, while binary operators require two operands. Most operators in Visual Basic are binary operators.
The VB arithmetic operators provide basic manipulation of integer and floating point numbers. They could be called "the calculator operators," since most of them appear on even the most basic four-function calculator.
+ (Addition)
The addition operator adds numeric expressions together and returns the result.
result = expression1 + expression2
When used with string operands, the + operator acts like the & string concatenation operator, as described below.
+ (Unary Plus)
Usually, the + operator only appears as a binary operator. But it can be used in a unary form. In this usage, when placed immediately before a number or numeric expression, it ensures that the expression retains its sign, either positive or negative. Since expressions retain their sign by default, the unary plus operator is redundant and rarely used.
result =+expression