3.1. Working with Classes and Objects

The advantage of OOP is that it facilitates code reuse. When you drag-and-drop a Button control onto a form, you don't worry about how it works; that's been taken care of by the control's designer. In addition, you're free to use as many Button controls on your form as you need and to modify each as required by changing its caption, color, shape, and through event handling even behavior. You can think of OOP as a set of tools that brings the same reusability you've grown accustomed to with VB 6 controls to the code you write to power your applications.

To understand OOP, you need to know about classes and objects. A class is like a template; it defines the essential features of some thing. A good analogy to a class is your concept of a car. When you hear the word "car," you no doubt quickly think of a vehicle with wheels, gas and brake pedals, a steering wheel, and so on before you think of a specific make. An object, on the other hand, is an instance of a class. A BMW sitting on a lot is a specific make of a car and, although it shares certain key features with every other car in the world, it is, like an object, a unique version, or instance, of the more general car class. A BMW is related to the general notion of a car as an object is to its defining class.

A car, regardless of its make, can be counted on to have a variety of properties, such as a color, some number of doors, and seats that are made of leather or vinyl. A class also has properties, as you'll see shortly, and you can assign them values and also find out what values have been assigned (though restrictions do apply).

A car also has certain behaviors and "knows" (in the hands of an experienced driver) how to accelerate, turn left, turn right, decelerate, or come to a stop. Every car includes the controls you need to make it do your bidding, and you expect to find them in more or less the same place regardless of make. A class has behaviors as well. These are defined by its methods.

When you step on the brake pedal of your car, the braking system gets to work to slow the vehicle. As a driver, you don't need to understand the inner workings of the braking system; you just need to know where to find the brake pedal and when to step on it. Likewise, when you use a method in a class, you need not understand its inner workings. All you need to know is how to invoke it, and what you can expect it to do.

3.1.1. Using the .NET Classes

Unlike VB 6, VB 2005 gets much of its work done by calling on the hundreds of classes provided by the .NET Framework 2.0, rather than the predefined functions of the traditional Visual Basic runtime or older COM-based libraries such as ADO (both of which are still supported in VB 2005). Collectively, these classes are known as the .NET Framework Class Library, or FCL.

VB 6 Functions and the .NET Base Class Library

Because VB 2005 is a language designed to work with the .NET Framework, some changes to the language are necessary to maintain interoperability with the Common Language Runtime. You've already seen many of these in Chapter 2.

The Common Language Runtime (CLR) is the heart of the .NET Framework. The CLR manages code execution and provides application services such as security, memory management, and cross-language integration.

In VB 2005, the .NET Framework includes new libraries that provide equivalent functionality to many VB 6 keywords and functions (although these VB 6 functions are still available in VB 2005).

To see the list of changes to the VB 6 language and their equivalents in Visual Basic 2005, refer to the MSDN Help Topic "Programming Element Support Changes Summary."

To see how application development (such as Windows and web development) have changed in Visual Basic 2005, refer to MSDN Help Topic "Help for Visual Basic 6.0 Users."

The .NET Class Libraries are contained in multiple DLLs, known as assemblies, and loaded only when they're needed. This has the advantage of reducing the time it takes to load a managed application. Due to the large number of classes that ship with the .NET Framework, Microsoft has logically grouped them into namespaces. Namespaces are used to arrange classes in groups based on the functionality they provide. For example, the System namespace contains fundamental classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.

Here are some other useful namespaces in the .NET Framework:


The System namespace contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.


The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables, and dictionaries.


The System.Windows.Forms namespace contains classes for creating Win-dows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system.


The System.Web.UI namespace provides classes and interfaces that allow you to create ASP.NET server controls and pages that will appear in your web applications as user interface elements.


The System.Data namespace consists mostly of the classes that constitute the ADO.NET architecture for data access. The ADO.NET architecture enables you to build components that efficiently manage data from multiple data sources.

When you create a Visual Basic project in Visual Studio 2005, the IDE ensures that references to the most commonly used base class library assemblies are added before you begin to write code. However, if you need to use a type that is in an assembly you've not already referenced, you will need to add the missing reference to your code. The Add Reference dialog box in Visual Studio allows you to add an assembly without having to write code.

A .NET Framework Class Library assembly may contain several namespaces. For example, the System.Data.dll assembly contains several namespaces for classes that perform data access. To use the relevant libraries in the assembly, you need to use the Imports keyword to import them for use in your application, such as:

 Imports System.Data Imports System.Data.SqlClient Imports System.Data.OleDb 

For example, if you want to create a SqlDataReader object that reads data from a Microsoft SQL server, you would need to import the System.Data. SqlClient namespace with an Imports statement at the top of your code.

Once you have correctly referenced the namespace, you can then reference a SqlDataReader object in your code like this:

 Dim reader As SqlDataReader 

Alternatively, you can use the SqlDataReader object by its fully qualified name, like this:

 Dim reader As _ System.Data.SqlClient.SqlDataReader 

The first approach is the recommended one, as it makes your code much more readable.

Commonly Referenced DLLs

Depending on the type of project you create, Visual Studio automatically adds references to the DLLs you are most likely to need. For Windows applications, these include:

  • System.dll

  • System.Deployment.dll

  • System.Drawing.dll

  • System.Windows.Forms.dll

  • System.Data.dll

  • System.Xml.dll

For web applications, the following DLLs are referenced by default:

  • System.dll

  • System.Web.dll

  • System.Data.dll

  • System.Xml.dll

  • System.Drawing.dll

3.1.2. Creating Objects

In the .NET world, applications are built with classes and objects, either your own or those provided by the .NET Framework. To fully use the power of VB 2005, you need to understand how to work with them.

Since it's available, let's use the Stack class provided in the System.Collections namespace of the .NET Framework to illustrate how you can get productive with OOP. You'll see how to define your own version later in this chapter (see "Defining a Class," later in this chapter).

What Is a Stack?

A stack is a data structure that works based on the last in, first out (LIFO) principle. This means that the last item put on the stack is the first item that can be taken off, like a physical stack of plates.

Stacks are used quite often in programming. They are used to store subroutine arguments and return addresses. Stacks are also commonly used to evaluate mathematical expressions.

Adding an item to a stack is known as a push operation and removing an item from a stack is known as a pop operation.

The .NET Framework includes a Stack class, which is located in the System.Collections namespace.

VB 6 Tip: VB 6 does not provide a ready-to-use Stack class.

To drive a car, you need a real one, whether it's your own or a BMW you take for a spin at your local dealership. Likewise, to use a Stack class, whether it's your own or the .NET version, you must instantiate that is, create an instance of the class. Instantiating a class is, you might say, a classic example of reuse. From a single design, you can create as many instances of a Stack as you need for your application, just as the designs embedded in an automobile manufacturing plant are used to build multiple versions of the same car. You'll learn about customizing classes later in this chapter.

There are several ways to instantiate a Stack object, so let's take a look at them.

You use the Dim keyword to declare that a variable s1, in this case is of type Stack, just as you did for normal VB variables and constants in Chapter 2.

 Dim s1 As Stack 

You use the New keyword to instantiate a Stack object (i.e., create an instance of the class):

 s1 = New Stack 

You can also declare and instantiate an object in a single statement. The following two statements, for example, are equivalent:

 Dim s2 As New System.Collections.Stack ' or Dim s2 As System.Collections.Stack = New System.Collections.Stack 

The parentheses following the name of a class are optional. (I will not be using parentheses for the class names in the examples throughout this book.) The following two statements are the same:

 Dim s1 As New System.Collections.Stack Dim s1 As New System.Collections.Stack() 

VB 6 Tip: In VB 6, assigning an object to a variable requires the use of the Set keyword:

 '---VB6--- Set obj = New Class1 

This has confused VB 6 developers who are sometimes unsure of when to use the Set keyword.

With VB 2005, Microsoft has eliminated this confusion, since the Set keyword is no longer used for object assignment:

 '---VB2005--- obj = New Class1 

Note that if you precede the previous statement with the Set keyword, Visual Studio 2005 will automatically remove it.

To use the Stack object, you could push in some values via the Push method:

 '---Push items into the stack--- s1.Push("Hello ") s1.Push("Visual ") s1.Push("Basic ") s1.Push("2005") 

Get a count of the number of items in the Stack object by using the Count property:

 '---Get the item count in the stack--- Dim itemCount As Integer = s1.Count 

You could also pop the items out of the Stack object by using the Pop method:

 '---Pop the items out from the stack--- For i As Integer = 0 To s1.Count - 1 MsgBox(s1.Pop()) ' strings are printed in the  ' reverse order they were pushed Next 

Example 3-1 shows the complete code needed to use the Stack class.

Example 3-1. Using a Stack object
 Dim s1 As New System.Collections.Stack '---Push items into the stack--- s1.Push("Hello ") s1.Push("Visual ") s1.Push("Basic ") s1.Push("2005") '---Get the item count in the stack--- Dim itemCount As Integer = s1.Count '---Pop the items out from the stack--- For i As Integer = 0 To s1.Count - 1  MsgBox(s1.Pop()) ' strings are printed in the   ' reverse order they were pushed Next 

3.1.3. Comparing Objects

If you want to check to see whether two variables are referencing the same object, you need to use the Is operator (the = operator cannot be used), as demonstrated in Example 3-2.

Example 3-2. Comparing two objects
 Dim s1, s2 As System.Collections.Stack s1 = New System.Collections.Stack s2 = New System.Collections.Stack If s1 Is s2 Then MsgBox("objs are the same") Else '---this will be printed--- MsgBox("ojs are not the same") End If '---Assigning s2 to s1; essentially s1 and s2 will '---now point to the same object s1 = s2 If s1 Is s2 Then '---this will be printed--- MsgBox("objs are the same") Else MsgBox("objs are not the same") End If 

Note that the Is operator is used only for comparing object references (if they are all referencing the same object); it cannot be used to compare the values of objects.

Besides the Is operator, you can also use the Equals method (available on all .NET objects) to compare the equality of two objects (that is, if the two objects are pointing to the same reference), like this:

 If s1.Equals(s2) Then MsgBox("objs are the same") Else MsgBox("objs are not the same") End If … 

Shared Methods

Typically, you need to create an instance of a class before you can invoke its methods, as you've seen in the preceding example. However, there are exceptions to this rule. As an example, consider the File class in the System.IO namespace. The File class contains methods for file manipulation, such as copying, deleting, writing, reading, etc. To use the File class, you don't need to create an instance of the class; you simply invoke its method directly:

 '---copies a file--- System.IO.File.Copy("C:\File1.txt", "C:\File1.bak") 

The methods in the File class are known as static methods, the general term used by most object oriented languages, or as shared methods, the term and keyword used by VB 2005. A shared method can be invoked without creating an instance of its class.

Visual Basic 2005 Jumpstart 2005
Visual Basic 2005 Jumpstart
ISBN: 059610071X
EAN: 2147483647
Year: 2005
Pages: 86
Authors: Wei-Meng Lee

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net