BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


VB.NET Language in a Nutshell
VB.NET Language in a Nutshell, Second Edition

By Steven Roman, Ph.D., Ron Petrusha, Paul Lomax

Cover | Table of Contents | Colophon


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 the world's most widely used programming language, with an installed base of somewhere between three and five million developers (depending on the particular source you use and whether the estimate includes only the retail versions of the Visual Basic product or the hosted version of Visual Basic for Applications (VBA) as well).
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 release of its new .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 VB.NET, Microsoft focused on creating a unified version of 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 drives the individual applications in the Microsoft Office 2000 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 2000. With the release of VB.NET, this emphasis on a unified programming language has, for the moment at least, faded into the background, as the hosted version of Visual Basic continues to be VBA rather than VB.NET.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why VB.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 whose release 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 loading or the window being resized). In other words, Visual Basic's initial success was due to its ease of use, which in turn reflected that Visual Basic offered a 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 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 itself.
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 VB.NET?
VB.NET is a programming language designed to create applications that work with Microsoft's new .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 ("DLL hell") when developing new versions of COM components, and the need for developers to write a certain amount of code (mostly in C++) to handle the COM "plumbing." In contrast to VB, with its reliance on COM, VB.NET 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 language. Yet the debate persists about whether Visual Basic is a "true" object-oriented language or whether it only supports limited features of object orientation.
The debate centers around Visual Basic's support for inheritance, an object- oriented programming concept that allows a class to derive its properties and its functionality from another class. Proponents of the view that Visual Basic is object- oriented point to Visual Basic's support for interface-based programming and the use of virtual base classes. Yet relatively few VB programmers take advantage of interface-based programming. And interface-based programming itself does not allow a derived class to inherit the functionality of a base class; only virtual base classes can be inherited using the Implements keyword.
While the object-oriented character of previous versions of VB may be in doubt, there is no question that VB.NET is an object-oriented programming language. In fact, even if VB.NET is used to write what appears to be procedural code, it is object-oriented "under the hood," so to speak. Let's take as a simple example the clearly procedural, nonobject-oriented program shown in Example 1-3. If we use ILDASM (.NET's intermediate language disassembler) to look at the IL generated for this source code (see Figure 1-1), we 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 VB.NET?
With its language enhancements and its tight integration into the .NET Framework, Visual Basic is a thoroughly modernized language that will likely become the premier development tool 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 unsuitable 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, VB.NET emerges as an equal player; Microsoft's claim of language independence — that programming language should be a lifestyle choice, rather than a choice forced on the developer by the character of a project — is realized in the .NET platform.
This means that VB.NET can be used to create a wide range of applications and components, including the following:
  • Windows console mode applications
  • Standard Windows applications
  • Windows services
  • Windows controls and Windows control libraries
  • Web (ASP.NET) applications
  • Web services
  • Web controls and web control libraries
  • .NET classes and namespaces
  • Accessing application object models (such as those of the individual applications in the Microsoft Office suite) using COM automation
Most importantly, for the first time with the release of VB.NET, Visual Basic becomes an all-purpose development environment for building Internet applications, an area in which it has traditionally been weak. This means that the release of this newest version should revitalize Visual Basic, allowing it to remain the tool of choice for developing state-of-the-art software for the next generation of software development.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Program Structure
VB.NET, unlike previous versions of Visual Basic, is fully object-oriented. Also unlike previous versions, VB.NET is fully integrated with its underlying platform, the .NET Framework and the .NET Common Language Runtime. As shown in this chapter, these two factors, perhaps more than any others, influence the structure of a VB.NET program.
Any Visual Basic executable — i.e., a Windows Forms or Windows console application — has a single application-level entry point, a subroutine named Main. Main must be a method of the executed class.
The web applications (either ASP.NET applications or web service applications) that you develop with Visual Studio are not executables. They exist as dynamic link libraries (DLLs) in the system's disk storage. ASP.NET applications may also rely on just-in-time compilation and be resident solely in memory.
Main must not only exist, it must also be:
A public routine
In VB 6, Main could be either public or private. In VB.NET, it must be public to be visible as an entry point.
A static or shared routine
Its declaration must include the Shared keyword. A single Main method must be shared by all application instances; it cannot be an instance method. Thus, all methods called by Main must also be static (or shared) methods; a shared method is unable to invoke an instance method.
This section focuses on executable programs. These programs exclude code libraries, as well as ASP.NET applications and web service applications, all of which are compiled as dynamic link libraries.
The requirement that there must be a subroutine named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting a VB Program to Run
Any Visual Basic executable — i.e., a Windows Forms or Windows console application — has a single application-level entry point, a subroutine named Main. Main must be a method of the executed class.
The web applications (either ASP.NET applications or web service applications) that you develop with Visual Studio are not executables. They exist as dynamic link libraries (DLLs) in the system's disk storage. ASP.NET applications may also rely on just-in-time compilation and be resident solely in memory.
Main must not only exist, it must also be:
A public routine
In VB 6, Main could be either public or private. In VB.NET, it must be public to be visible as an entry point.
A static or shared routine
Its declaration must include the Shared keyword. A single Main method must be shared by all application instances; it cannot be an instance method. Thus, all methods called by Main must also be static (or shared) methods; a shared method is unable to invoke an instance method.
This section focuses on executable programs. These programs exclude code libraries, as well as ASP.NET applications and web service applications, all of which are compiled as dynamic link libraries.
The requirement that there must be a subroutine named Main capable of serving as the executable's entry point is clear in a console application like the one shown in Example 2-1. The routine creates a module named modMain; that module in turn contains a subroutine named Main, which is the sole executable routine in the application. At runtime, Main serves as the program entry point; the Common Language Runtime finds the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Structure of a VB Program
Broadly speaking, programs can be either procedure driven or event driven . In a procedure-driven program, program flow is predefined. A classic example is a console application: program flow begins at the program entry point (in the case of a .NET console application, it begins with the Main routine) and proceeds along a predictable path until it reaches program termination. In an event-driven program, on the other hand, program flow is not predetermined and is instead controlled by external events (i.e., by the program's interaction with the user and the system), and possibly by internal events as well.
From the perspective of program structure, the difference between procedure-driven and event-driven programs is less sharp than is usually thought. Both rely on a procedure as an entry point, which in turn can call other functions and subroutines that are visible to it. The major difference is that a procedure-driven program has a single entry point, whereas an event-driven program has multiple entry points. For event-driven programs, these entry points (in addition to the required Main procedure) are event handlers , which are invoked automatically by the .NET Common Language Runtime in response to an event within the code itself or in its environment.
Therefore, regardless of whether an application is procedure driven or event driven, Visual Basic code can be divided into three main categories:
Entry point code
For procedural applications, this code is a routine named Main. For an event-driven application, it is a routine named Main, supplemented by code that you write to handle events such as a button being clicked by the user. These latter procedures are called event handlers.
Custom procedures
In these procedures, you create the main functionality of your application. When these custom procedures are located within a class, they are termed methods and are typically used to perform an operation.
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: Variables and Data Types
Many programmers take the concept of a variable for granted. In this chapter, we take a close look at variables and their properties, discussing such things as the scope and lifetime of a variable.
A variable can be defined as an entity that has the following six properties:
Name
A variable's name is used to identify the variable in code. In VB.NET, a variable name can start with a Unicode alphabetic character or an underscore, and can be followed by additional underscore characters or various Unicode characters, such as alphabetic, numeric, formatting, or combined characters.
Address
Every variable has an associated memory address, which is the location in memory at which the variable's value is stored. Note that in many circumstances, the address of a variable will change during its lifetime, so it would be dangerous to make any assumptions about this address.
Type
The type of a variable, also called its data type, determines the possible values that the variable can assume. We discuss data types in detail later in the chapter.
Value
The value of a variable is the contents of the memory location at the address of the variable. This is also sometimes referred to as the r-value of the variable, since it is what really appears on the right side of an assignment statement. For instance, in the code:
Dim i As Integer
Dim j As Integer
i = 5
j = i
the final statement can be read as "assign the value of i to memory at the address of j." For similar reasons, the address of a variable is sometimes called its
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 the variable in code. In VB.NET, a variable name can start with a Unicode alphabetic character or an underscore, and can be followed by additional underscore characters or various Unicode characters, such as alphabetic, numeric, formatting, or combined characters.
Address
Every variable has an associated memory address, which is the location in memory at which the variable's value is stored. Note that in many circumstances, the address of a variable will change during its lifetime, so it would be dangerous to make any assumptions about this address.
Type
The type of a variable, also called its data type, determines the possible values that the variable can assume. We discuss data types in detail later in the chapter.
Value
The value of a variable is the contents of the memory location at the address of the variable. This is also sometimes referred to as the r-value of the variable, since it is what really appears on the right side of an assignment statement. For instance, in the code:
Dim i As Integer
Dim j As Integer
i = 5
j = i
the final statement can be read as "assign the value of i to memory at the address of j." For similar reasons, the address of a variable is sometimes called its l-value.
Scope
The scope of a variable determines where in a program that variable is visible to the code. Scope is discussed in detail in the next section.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Declaring Variables and Constants
A variable declaration is an association of a variable name with a data type. In and of itself, this does not imply variable creation. However, for nonobject variables, a variable declaration does create a variable. A declaration such as:
Dim x As Integer
creates an Integer variable named x. We can also write:
Dim x As Integer = New Integer(  )
which emphasizes the role of the constructor function for the Integer data type. (The constructor is the function that VB.NET uses to create the variable.)
When multiple variables are declared on the same line, if a variable is not declared with an explicit type declaration, then its type is that of the next variable with an explicit type declaration. Thus, in the line:
Dim x As Long, i, j, k As Integer, s As String
the variables i, j, and k have type Integer. (In VB 6, the variables i and j would have type Variant, which is VB 6's default data type.)
VB.NET permits the initialization of variables in the same line as their declaration (at long last!). Thus, we may write:
Dim x As Integer = 5
to declare an Integer variable and initialize it to 5. Similarly, we can declare and initialize more than one variable on a single line:
Dim x As Integer = 6, y As Integer = 9
Note that in this case, each variable that you declare must explicitly be assigned a data type. You cannot assign each variable an explicit value without explicitly declaring the data type of each variable.
Object variables are declared in the same manner:
Dim obj As MyClass
However, this declaration does not create an object variable, and the variable is equal to Nothing at this point. Object creation requires an explicit call to the object's constructor, as in:
Dim obj As New MyClass(  )
or:
Dim obj As MyClass = New Myclass(  )
or:
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. Thus, each of the languages in the .NET Framework (VB, C#, JScript, and Managed C++) implements a subset of a common set of data types. We say subset because, unfortunately, not all of the CTS types are implemented by VB.NET. For instance, the CTS includes some unsigned integer data types that are not implemented in VB.
As an aside, it is possible to use the VB-unsupported data types in VB by direct use of the corresponding Framework Class Library class. Here is an example illustrating the ability to use the unsigned 16-bit integer data type, whose range of values is 0 to 65,535. Note the use of the ToUInt16 method of the Convert class to actually get an unsigned 16-bit integer:
Dim ui As UInt16
ui = Convert.ToUInt16(65535)
MsgBox(ui.ToString)
Thus, the native VB data types are wrappers for the CTS data types. To illustrate, the VB Integer data type is a wrapper for the Int32 structure that is part of the .NET Framework's System namespace. One of the members of the Int32 structure is MaxValue, which returns the maximum value allowed for this data type. Thus, even though MaxValue is not officially part of VB.NET (nor is it mentioned in the VB documentation), we can write:
Dim i As Integer
MsgBox(i.Maxvalue)   ' Displays 2147483647
The types defined in the CTS fall into three categories:
  • Value types
  • Reference types
  • Pointer types
However, pointer types are not implemented in VB, so we will not discuss these types.
The difference between value and reference types is how variables of the corresponding type represent that type. When a value-type variable is defined, as in:
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 data type is a fundamental data type in most languages, including Visual Basic. An array is used to store a collection of similar data types or objects.
Many authors of programming books misuse the terms associated with arrays, so let's begin by establishing the correct terminology. In fact, if you will indulge us, we would like to begin with a formal definition of the term array.
Let S1, S2 ..., SN be finite sets, and let T be a data type (such as Integer). Then an array of type T is a function:
arr:S1 · S2 · ... · SN  T
where S1 · S2 · ... · SN is the Cartesian product of the sets S1, S2 ..., SN. (This is the set of all n-tuples whose coordinates come from the sets Si.)
For arrays in VB.NET (and the other languages that implement the Common Language Runtime), the sets Si must have the form:
Si={0,1,...,Ki}
In other words, each set Si is a finite set of consecutive integers starting with 0.
Each position in the Cartesian product is referred to as a coordinate of the array. For each coordinate, the integer Ki is called the upper bound of the coordinate. The lower bound is 0 for all arrays in VB.NET.
The number N of coordinates in the domain of the function arr is called the dimension (or sometimes rank) of the array. Thus, every array has a dimension (note the singular); it is not correct to refer to the dimensions of an array (note the plural). An array of dimension 1 is called a one-dimensional array, an array of dimension 2 is called a two-dimensional array, and so on.
Along with a dimension, every array has a size. For instance, the one-dimensional array:
arr:{0,1,...,5}  T
has size 6. The two-dimensional array:
arr:{0,1,...,5}·{0,1,...,8}  T
has size 6·9. The three-dimensional array:
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 Variables and Their Binding
In VB.NET, classes and their objects are everywhere. Of course, there are the classes and objects that we create in our own applications. There are also the classes in the .NET Framework Class Library. In addition, many applications take advantage of the objects that are exposed by other applications, such as ActiveX Data Objects (ADO), Microsoft Word, Excel, Access, various scripting applications, and more. The point is that for each object we want to manipulate, we will need to declare a variable of that class type. For instance, if we create a class named CPerson, then in order to instantiate a CPerson object, we must declare a variable:
Dim APerson As CPerson
Similarly, if we decide to use the ADO Recordset object, we will need to declare a variable of type ADO.Recordset:
Dim rs As ADO.Recordset
Even though object variables are declared in the same manner as nonobject variables, there are some significant differences. In particular, the declaration:
Dim obj As MyClass
does not create an object variable — it only binds a variable name with a class name. To actually construct an object and set the variable to refer to that object, we need to call the constructor of the class. This function, discussed in detail in Chapter 4, is responsible for creating objects of the class.
Constructors are called using the New keyword, as in:
Dim obj As MyClass = New MyClass(  )
or:
Dim obj As MyClass
obj = New MyClass(  )
VB.NET also provides a shortcut that does not mention the constructor explicitly:
Dim obj As New MyClass(  )
(In earlier versions of VB, we use the Set statement, which is no longer supported.)
The object-variable declaration:
Dim obj As Class1
explicitly mentions the class from which the object will be created (in this case it is Class1). Because of this, VB can obtain and display information about the class members, as we can see in VB's Intellisense, shown in Figure 3-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!
The Collection Object
VB.NET implements a special object called the Collection object that acts as a container for objects of all types. In fact, Collection objects can hold other objects, as well as nonobject data.
In some ways, the Collection object is an object-oriented version of the Visual Basic array. It supports the following four methods:
Add
Adds an item to the collection. Along with the data itself, you can specify a key value by which the member can be referenced.
Count
Returns the number of items in the collection.
Item
Retrieves a member from the collection either by its index (or ordinal position in the collection) or by its key (assuming that a key was provided when the item was added to the collection).
Remove
Deletes a member from the collection using the member's index or key.
For example, the following code defines a collection object named colStates to hold information about U.S. states and then adds two members to it, using the state's two-letter abbreviation as a key:
Dim colStates As New Collection
colStates.Add("New York", "NY")
colStates.Add("Michigan", "MI")
Like members of an array, the members of a collection can be iterated using the For Each...Next construct. Also like arrays, collection members are accessible by their index value, although the lower bound of a collection object's index is always 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!
Parameters and Arguments
The terms parameter and argument are often used interchangeably, although they have entirely different meanings. Let us illustrate with an example. Consider the following function, which replicates a string a given number of times:
Function RepeatString(ByVal sInput As String, ByVal iCount As Integer) _
                      As String
    Dim i As Integer
    For i = 1 To iCount
        RepeatString = RepeatString & sInput
    Next
End Function
The variables sInput and iCount are the parameters of this function. Note that each parameter has an associated data type.
Now, when we call this function, we must replace the parameters by variables, constants, or literals, as in:
s = RepeatString("Donna", 4)
The items that we use in place of the parameters are called arguments.
Arguments can be passed to a function in one of two ways: by value or by reference. Incidentally, argument passing is often called parameter passing, although it is the arguments and not the parameters that are being passed.
The declaration of RepeatString given earlier contains the keyword ByVal in front of each parameter. This specifies that arguments are passed by value to this function. Passing by value means that the actual value of the argument is passed to the function. This is relevant when an argument is a variable. For instance, consider the following code:
Sub Inc(ByVal x As Integer)
    x = x + 1
End Sub

Dim iAge As Integer = 20
Inc(iAge)
Msgbox(iAge)
The final line:
Msgbox(iAge)
actually displays the number 20. In other words, the line:
Inc(iAge)
does nothing. The reason is that the argument iAge is passed to the procedure Inc by value. Since only the value (in this case 20) is passed, that value is assigned to a local variable named x within the procedure. This local variable is increased to 21, but once the procedure ends, the local variable is destroyed. The variable
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Introduction to Object-Oriented Programming
In this chapter, we present a brief and succinct introduction to object-oriented programming. Since this is not a book on object-oriented programming per se, we will confine our attention to those topics that are important to VB.NET programming.
As you may know, Visual Basic has implemented some features of object-oriented programming since Version 4. However, in terms of object-orientation, the move from Version 6 to VB.NET has been dramatic. Many people did not consider VB 6 (or earlier versions) to be a truly object-oriented programming language. Whatever your thoughts may have been on this matter, it seems clear that VB.NET is an object-oriented programming language by any reasonable definition of the term.
You may be saying to yourself: "I prefer not to use object-oriented techniques in my programming." This is something you could easily have gotten away with in VB 6. But in VB.NET, the structure of the .NET Framework — specifically the .NET Framework Class Library — as well as the documentation, is so object-oriented that you can no longer avoid understanding the basics of object-orientation, even if you decide not to use them in your applications.
It is often said that there are four main concepts in the area of object-oriented programming:
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism
Each of these concepts plays a significant role in VB.NET programming at one level or another. Encapsulation and abstraction are "abstract" concepts providing motivation for object-oriented programming. Inheritance and polymorphism are concepts that are directly implemented in VB.NET programming.
Simply put, an abstraction is a view of an entity that includes only those aspects that are relevant for a particular situation. For instance, suppose that we want to create a software component that provides services for keeping a company's employee information. For this purpose, we begin by making a list of the items relevant to our entity (an employee of the company). Some of these items are:
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 Learn Object-Oriented Techniques?
As you may know, Visual Basic has implemented some features of object-oriented programming since Version 4. However, in terms of object-orientation, the move from Version 6 to VB.NET has been dramatic. Many people did not consider VB 6 (or earlier versions) to be a truly object-oriented programming language. Whatever your thoughts may have been on this matter, it seems clear that VB.NET is an object-oriented programming language by any reasonable definition of the term.
You may be saying to yourself: "I prefer not to use object-oriented techniques in my programming." This is something you could easily have gotten away with in VB 6. But in VB.NET, the structure of the .NET Framework — specifically the .NET Framework Class Library — as well as the documentation, is so object-oriented that you can no longer avoid understanding the basics of object-orientation, even if you decide not to use them in your 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!
Principles of Object-Oriented Programming
It is often said that there are four main concepts in the area of object-oriented programming:
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism
Each of these concepts plays a significant role in VB.NET programming at one level or another. Encapsulation and abstraction are "abstract" concepts providing motivation for object-oriented programming. Inheritance and polymorphism are concepts that are directly implemented in VB.NET programming.
Simply put, an abstraction is a view of an entity that includes only those aspects that are relevant for a particular situation. For instance, suppose that we want to create a software component that provides services for keeping a company's employee information. For this purpose, we begin by making a list of the items relevant to our entity (an employee of the company). Some of these items are:
  • FullName
  • Address
  • EmployeeID
  • Salary
  • IncSalary
  • DecSalary
Note that we include not only properties of the entities in question, such as FullName, but also actions that might be taken with respect to these entities, such as IncSalary, to increase an employee's salary. Actions are also referred to as methods, operations, or behaviors. We will use the term methods, since this term is used by VB.NET.
Of course, we would never think of including an IQ property, since this would not be politically correct, not to mention discriminatory and therefore possibly illegal. Nor would we include a property called HairCount, which gives the number of hairs on the employee's right arm, because this information is of absolutely no interest to us, even though it is part of every person's being.
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
Generally speaking, a class is a software component that defines and implements one or more interfaces. (Strictly speaking, a class need not implement all the members of an interface. We discuss this later when we talk about abstract members.) In different terms, a class combines data, functions, and types into a new type. Microsoft uses the term type to include classes.
Under Visual Studio.NET, a VB class module is inserted into a project using the Add Class menu item on the Project menu. This inserts a new module containing the code:
Public Class ClassName

End Class
Although Visual Studio stores each class in a separate file, this isn't a requirement. It is the Class...End Class construct that marks the beginning and end of a class definition. Thus, the code for more than one class as well as one or more code modules (which are similarly delimited by the Module...End Module construct) can be contained in a single source code file.
The CPerson class defined in the next section is an example of a VB class module.
In VB.NET, class modules can contain the following types of members:
Data members
This includes member variables (also called fields) and constants.
Event members
Events are procedures that are called automatically by the Common Language Runtime in response to some action that occurs, such as an object being created, a button being clicked, a piece of data being changed, or an object going out of scope.
Function members
This refers to both functions and subroutines. A function member is also called a method. A class' constructor is a special type of method. We discuss constructors in 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!
Inheritance
Perhaps the best way to describe inheritance as it is used in VB.NET is to begin with an example.
The classes in a given application often have relationships to one another. Consider, for instance, our Employee information application. The Employee objects in the class CEmployee represent the general aspects common to all employees — name, address, salary, and so on.
Of course, the executives of the company will have different prerequisites than, say, the secretaries. So it is reasonable to define additional classes named CExecutive and CSecretary, each with properties and methods of its own. On the other hand, an executive is also an employee, and there is no reason to define different Name properties in the two cases. This would be inefficient and wasteful.
This situation is precisely what inheritance is designed for. First, we define the CEmployee class, which implements a Salary property and an IncSalary method:
' Employee class
Public Class CEmployee
    ' Salary property is read/write
    Private mdecSalary As Decimal
    Property Salary(  ) As Decimal
        Get
            Salary = mdecSalary
        End Get
        Set
            mdecSalary = Value
        End Set
    End Property
    Public Overridable Sub IncSalary(ByVal sngPercent As Single)
        mdecSalary = mdecSalary * (1 + CDec(sngPercent))
    End Sub
End Class
Next, we define the CExecutive class:
' Executive Class
Public Class CExecutive
    Inherits CEmployee
    ' Calculate salary increase based on 5% car allowance as well
    Overrides Sub IncSalary(ByVal sngPercent As Single)
        Me.Salary = Me.Salary * CDec(1.05 + sngPercent)
    End Sub
End Class
There are two things to note here. First, the line:
Inherits CEmployee
indicates that the CExecutive class inherits the members of the CEmployee class. Put another way, an object of type CExecutive is also an object of type CEmployee. Thus, if we define an object of type CExecutive:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Interfaces, Abstract Members, and Classes
We have alluded to the fact that a class may implement all, some, or none of the members of the interfaces that it defines. Any interface member that does not have an implementation is referred to as an abstract member. The purpose of an abstract member is to provide a member signature (a template, if you will) that can be implemented by one or more derived classes, generally in different ways.
Let us clarify this with an example. Recall from our discussion of inheritance that the CEmployee class defines and implements an IncSalary method that increments the salary of an employee. Recall also that the CExecutive and CSecretary derived classes override the implementation of the IncSalary method in the base class CEmployee.
Suppose that, in a more complete employee model, there is a derived class for every type of employee. Moreover, each of these derived classes overrides the implementation of the IncSalary method in the base class CEmployee. In this case, the implementation of IncSalary in the base class will never need to be called! So why bother to give the member an implementation that will never be used?
Instead, we can simply provide an empty IncSalary method, as shown here:
' Employee class
Public Class CEmployee

    . . .

    Public Overridable Sub IncSalary(ByVal sngPercent As Single)
    End Sub

End Class
Alternatively, if we want to require that all derived classes implement the IncSalary method, we can use the MustOverride keyword, as shown here:
' Employee class
Public MustInherit Class CEmployee

    . . .

    Public MustOverride Sub IncSalary(ByVal sngPercent As Single)

End Class
As mentioned earlier, when using MustOverride, there is no End Sub statement associated with the method. Note also that when using the MustOverride keyword, Microsoft requires that the class be declared with the MustInherit keyword. This specifies that we cannot create objects of type CEmployee.
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 and Overloading
Fortunately, we don't need to go into the details of polymorphism and overloading, which is just as well, because they tend to be both confusing and ambiguous. For instance, some computer scientists say that overloading is a form of polymorphism, whereas others say it is not. We will discuss only those issues that are directly relevant to the .NET Framework.
Overloading refers to an item being used in more than one way. Operator names are often overloaded. For instance, the plus sign (+) refers to addition of integers, addition of singles, addition of doubles, and concatenation of strings. Thus, the plus symbol (+) is overloaded. It's a good thing, too; otherwise, we would need separate symbols for adding integers, singles, and doubles.
Function names can also be overloaded. For instance, the absolute value function, Abs, can take an integer parameter, a single parameter, or a double parameter. Because the name Abs represents several different functions, it is overloaded. In fact, if you look at the documentation for the Abs member of the Math class (in the System namespace of the Framework Class Library), you will find the following declarations, showing the different functions using the Abs name:
Overloads Public Shared Function Abs(Decimal) As Decimal
Overloads Public Shared Function Abs(Double) As Double
Overloads Public Shared Function Abs(Integer) As Short
Overloads Public Shared Function Abs(Integer) As Integer
Overloads Public Shared Function Abs(Long) As Long
Overloads Public Shared Function Abs(SByte) As SByte
Overloads Public Shared Function Abs(Single) As Single
Note the use of the Overloads keyword, which tells VB that this function is overloaded.
Specifically, a function name is overloaded when two defined functions use the same name but have different argument signatures. For instance, consider a function that retrieves a current account balance. The account could be identified either by the person's name or by the account number. Thus, we might define two functions, each called GetBalance:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessibility in Class Modules
The notion of accessibility (or scope) in class modules is more involved than it is in standard modules. As far as local variables (block-level and procedure-level) are concerned, there is no difference — we have block scope and procedure-level scope.
However, members of a class module can be assigned one of the following access modifiers:
  • Public
  • Private
  • Friend
  • Protected
  • Protected Friend
(For standard modules, only Public, Private, and Friend are allowed.)
Actually, we can dispense with the Protected Friend modifier in one statement: Protected Friend is equivalent to Protected or Friend. Put another way, if Protected sets a specific range of accessibility (or inheritance — see below) and Friend sets a different range, then Protected Friend sets accessibility to the union of those ranges — if a member falls into either range, it passes the accessibility (or inheritance) criterion.
Note that class modules themselves can be declared with any one of the three access modifiers: Public, Private, or Friend (Protected is not allowed). When a class module declaration specifies one of these access modifiers, this simply restricts all of its members to that level of access, unless a member's access is further restricted by the access modifier on the member declaration itself. For instance, if the class has Friend
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: The .NET Framework: General Concepts
In this chapter, we discuss some of the main concepts in the .NET Framework. This is intended as a general overview, just to give you the "lay of the .NET land," so to speak. For more information, see Thuan Thai and Hoang Q. Lam's .NET Framework Essentials (O'Reilly, 2001).
The notion of a namespace plays a fundamental role in the .NET Framework. In general, a namespace is a logical grouping of types for the purpose of identification. For example, 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 pay checks, the executive John Smith won't be happy if he rushes to the table when the paymaster calls out his name and the envelope contains the custodian John Smith's pay check.
To resolve the naming ambiguity, the business can simply 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
The .NET Framework Class Library (FCL), which we look at in more detail in Chapter 6, consists of several thousand classes and other types (such as interfaces, structures, and enumerations) that are divided into over 90 namespaces. These namespaces provide basic system services, such as:
  • Basic and advanced data types and exception handling (the System namespace)
  • Data access (the System.Data namespace)
  • User-interface elements for standard Windows applications (the System.Windows.Forms namespace)
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 for the purpose of identification. For example, 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 pay checks, the executive John Smith won't be happy if he rushes to the table when the paymaster calls out his name and the envelope contains the custodian John Smith's pay check.
To resolve the naming ambiguity, the business can simply 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
The .NET Framework Class Library (FCL), which we look at in more detail in Chapter 6, consists of several thousand classes and other types (such as interfaces, structures, and enumerations) that are divided into over 90 namespaces. These namespaces provide basic system services, such as:
  • Basic and advanced data types and exception handling (the System namespace)
  • Data access (the System.Data namespace)
  • User-interface elements for standard Windows applications (the System.Windows.Forms namespace)
  • User-interface elements for web applications (the System.Web.UI namespace)
In fact, the VB.NET language itself is implemented as a set of classes belonging to the Microsoft.VisualBasic namespace. (The C# and JScript languages are also implemented as a set of classes in corresponding namespaces.)
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 (CLR), Managed Code, and Managed Data