Lesson 2: The .NET Base Class Library

Lesson 2: The .NET Base Class Library

The .NET base class library is a collection of object-oriented types and interfaces that provide object models and services for many of the complex programming tasks you will face. Most of the types presented by the .NET base class library are fully extensible, allowing you to build types that incorporate your own functionality into your managed code. This lesson introduces some of the .NET base class library namespaces and describes how to reference the library and use its types and methods.

After this lesson, you will be able to

  • Describe the .NET base class library

  • Explain the difference between value types and reference types

  • Create a reference to a namespace

  • Create an instance of a .NET Framework class and value type

Estimated lesson time: 30 minutes

The .NET Framework base class library contains the base classes that provide many of the services and objects you need when writing your applications. The class library is organized into namespaces. A namespace is a logical grouping of types that perform related functions. For example, the System.Windows.Forms namespace contains all the types that make up Windows forms and the controls used in those forms.

Namespaces are logical groupings of related classes. The namespaces in the .NET base class library are organized hierarchically. The root of the .NET Framework is the System namespace. Other namespaces can be accessed with the period operator. A typical namespace construction appears as follows:

System System.Data System.Data.SQLClient

The first example refers to the System namespace. The second refers to the System.Data namespace. The third example refers to the System.Data.SQLClient namespace. Table 1.1 introduces some of the more commonly used .NET base class namespaces.

Table 1-1. Representative .NET Namespaces

Namespace

Description

System

This namespace is the root for many of the low-level types required by the .NET Framework. It is the root for primitive data types as well, and it is the root for all the other namespaces in the .NET base class library.

System.Collections

This namespace contains classes that represent a variety of different container types, such as ArrayList, SortedList, Queue, and Stack. You also can find abstract classes, such as CollectionBase, which are useful for implementing your own collection functionality.

System.ComponentModel

This namespace contains classes involved in component creation and containment, such as attributes, type converters, and license providers.

System.Data

This namespace contains classes required for database access and manipulations, as well as additional namespaces used for data access.

System.Data.Common

This namespace contains a set of classes that are shared by the .NET managed data providers.

System.Data.OleDb

This namespace contains classes that make up the managed data provider for OLE DB data access.

System.Data.SQLClient

This namespace contains classes that are optimized for interacting with Microsoft SQL Server.

System.Drawing

This namespace exposes GDI+ functionality and provides classes that facilitate graphics rendering.

System.IO

In this namespace, you will find types for handling file system I/O.

System.Math

This namespace is home to common mathematics functions such as extracting roots and trigonometry.

System.Reflection

This namespace provides support for obtaining information and dynamic creation of types at runtime.

System.Security

This namespace is home to types dealing with permissions, cryptography, and code access security.

System.Threading

This namespace contains classes that facilitate the implementation of multithreaded applications.

System.Windows.Forms

This namespace contains types involved in creating standard Windows applications. Classes that represent forms and controls reside here as well.

The namespace names are self-descriptive by design. Straightforward names make the .NET Framework easy to use and allow you to rapidly familiarize yourself with its contents.

Reference Types and Value Types

Types in the .NET Framework come in two varieties: value types and reference types. The primary difference between value types and reference types has to do with the way variable data is accessed. To understand this difference, a little background on memory dynamics is required.

Application data memory is divided into two primary components, the stack and the heap. The stack is an area of memory reserved by the application to run the program. The stack is analogous to a stack of dinner plates. Plates are placed on the stack one on top of another. When a plate is removed from the stack, it is always the last one to have been placed on top that is removed first. So it is with program variables. When a function is called, all the variables used by the function are pushed onto the stack. If that function calls additional functions, it pushes additional variables onto the stack. When the most recently called function terminates, all of its variables go out of scope (meaning that they are no longer available to the application) and are popped off the stack. Memory consumed by those variables is then freed up, and program execution continues.

The heap, on the other hand, is a separate area of memory reserved for the creation of reusable objects. The common language runtime manages allocation of heap memory for objects and controls the reclamation of memory from unused objects through garbage collection.

NOTE
Garbage collection is discussed further in Lesson 6 of this chapter.

All the data associated with a value type is allocated on the stack. When a variable of a value type goes out of scope, it is destroyed and its memory is reclaimed. A variable of a reference type, on the other hand, exists in two memory locations. The actual object data is allocated on the heap. A variable containing a pointer to that object is allocated on the stack. When that variable is called by a function, it returns the memory address for the object to which it refers. When that variable goes out of scope, the object reference is destroyed but the object itself is not. If any other references to that object exist, the object remains intact. If the object is left without any references, it is subject to garbage collection. (See Lesson 6 of this chapter.)

Examples of value types include primitives, such as Integer (int), Boolean (bool), Char (char), and so on, as well as user-defined types such as Structure (struct) and Enumeration (enum). Classes represent the majority of reference types. Other reference types include the interface, delegate, and array types. Classes and structures are discussed in Lesson 3 of this chapter, and other reference and value types are discussed in Chapter 3.

NOTE
Throughout this book, when Visual Basic and Visual C# terms are mentioned together, the Visual Basic term appears first, followed by the C# term in parentheses.

Using .NET Framework Types in Your Application

When you begin writing an application, you automatically begin with a reference to the .NET Framework base class library. You reference it so that your application is aware of the base class library and is able to create instances of the types represented by it.

Value Types

In Visual Basic .NET, you use the Dim statement to create a variable that represents a value type. In C#, you create a variable by declaring its type and then the variable name. The following code is an example:

Visual Basic .NET

Dim myInteger As Integer

Visual C#

int myInteger;

This line tells the runtime to allocate the appropriate amount of memory to hold an integer variable. Although this line creates the variable, it does not assign a value to it. You can assign a value using the assignment operator, as follows:

Visual Basic .NET

myInteger = 42

Visual C#

myInteger = 42;

You can also choose to assign a value to a variable upon creation, as shown in this example:

Visual Basic .NET

Dim myInteger As Integer = 42

Visual C#

int myInteger = 42;

NOTE
Although declaration and initialization on a single line was discouraged in Visual Basic 6, there is no performance drawback to single-line declaration and initialization in Visual Basic .NET.

Reference Types

Creating an instance of a type is a two-step process. The first step is to declare the variable as that type, which allocates the appropriate amount of memory for that variable but does not actually create the object. The following syntax declares an object:

Visual Basic .NET

Dim myForm As System.Windows.Forms.Form

Visual C#

System.Windows.Forms.Form myForm;

This line tells the runtime to set aside enough memory to hold a Form variable and assigns it the name myForm, but it does not actually create the Form object in memory. The second step, called instantiation, actually creates the object. An example of instantiation follows:

Visual Basic .NET

myForm = New System.Windows.Forms.Form()

Visual C#

myForm = new System.Windows.Forms.Form();

This line makes a call to the constructor method of the type System.Windows.Forms.Form by way of the New (new) keyword. The constructor is a special method that is invoked only at the beginning of an object s lifetime. It contains any code that must be executed for the object to work (assigning values to properties, for example). If any parameters were required by the constructor, they would be contained within the parentheses at the end of the line. The following example shows declaration and instantiation of a hypothetical Widget class that requires a string as a parameter in the constructor. For further discussion of the constructor, see Lesson 4 in this chapter.

Visual Basic .NET

Dim myWidget As Widget myWidget = New Widget("This string is required by the constructor")

Visual C#

Widget myWidget; myWidget = new Widget("This string is required by the constructor");

If desired, you can also combine both declaration and instantiation into a single statement. By declaring and instantiating an object in the same line, you reserve the memory for the object and immediately create the object that resides in that memory. Although there was a significant performance penalty for this shortcut in previous versions of Visual Basic, Visual Basic .NET and Visual C# are optimized to allow this behavior without any performance loss. The following example shows the one-step declaration and instantiation of a new Form:

Visual Basic .NET

Dim myForm As New System.Windows.Forms.Form()

Visual C#

System.Windows.Forms.Form myForm = new System.Windows.Forms.Form();

Both value types and reference types must be initialized before use. For class and structure fields in Visual Basic .NET, types are initialized with default values on declaration. Numeric value types (such as integer) and floating-point types are assigned zero; Boolean variables are assigned False; and reference types are assigned to a null reference.

In C#, variables of a reference type have a default value of null. It is recommended that you do not rely on the default value. These variables should not be used until they have been initialized.

Using Value Type and Reference Type Variables

A variable that represents a value type contains all the data represented by that type. A variable that represents a reference type contains a reference to a particular object. This distinction is important. Consider the following example:

Visual Basic .NET

Dim x, y As integer x = 15 y = x x = 30 ' What is the value of y?

Visual C#

int x, y; x = 15; y = x; x = 30; // What is the value of y? 

In this example, two integer variables named x and y are created. X is assigned a value of 15, and then y is assigned the value of x. Next the value of x is changed to 30, and the question is posed: what is the value of y? The answer to this question might seem obvious, and it is y = 15 because x and y are two separate variables and have no effect on each other when changed. When the line y = x is encountered, the value of x is copied to the value of y, and there is no further connection between the two variables.

This situation changes, however, in the case of reference types. Let s reconsider the previous example using a reference type (Form) instead of a value type.

Visual Basic .NET

Dim x, y As System.Windows.Forms.Form x = New System.Windows.Forms.Form() x.Text = "This is Form 1" y = x x.Text = "This is Form 2" ' What value does y.Text return?

Visual C#

System.Windows.Forms.Form x,y; x = new System.Windows.Forms.Form(); x.Text = "This is Form 1"; y = x; x.Text = "This is Form 2"; // What value does y.Text return? 

What value does y.Text return? This time, the answer is less obvious. Because System.Windows.Forms.Form is a reference type, the variable x does not actually contain a Form; rather, it points to an instance of a Form. When the line y = x is encountered, the runtime copies the reference from variable x to y. Thus, the variables x and y now point to the same instance of Form. Because these two variables refer to the same instance of the object, they will return the same values for properties of that object. Thus, y.Text returns This is Form 2 .

The Imports and Using Statements

Up to this point of the chapter, if you wanted to access a type in the .NET Framework base class library, you had to use the full name of the type, including every namespace to which it belonged. For example:

System.Windows.Forms.Form

This is called the fully-qualified name, meaning it refers both to the class and to the namespace in which it can be found. You can make your development environment aware of various namespaces by using the Imports (Visual Basic .NET) or using (Visual C#) statement. This technique allows you to refer to a type using only its generic name and to omit the qualifying namespaces. Thus, you could refer to System.Windows.Forms.Form as simply Form. In Visual Basic .NET, the Imports statement must be placed at the top of the code window, preceding any other statement (except Option). In Visual C#, the using statement must occur before any other namespace element, such as a class or struct. This example demonstrates use of this statement:

Visual Basic .NET

Imports System.Windows.Forms

Visual C#

using System.Windows.Forms;

When two types of the same name exist in more than one imported namespace, you must use the fully qualified name to avoid a naming conflict. Thus, if you are using MyNameSpaceOne and MyNameSpaceTwo, and each contains a Widget class, you would have to refer to MyNameSpaceOne.Widget or MyNameSpaceTwo.Widget to ensure the correct result.

In C#, you can resolve namespace conflicts such as these by creating an alias. An alias allows you to choose one name to refer to another class. You create an alias using the using keyword, as shown below:

Visual C#

using myAlias = MyNameSpaceTwo.Widget;

After implementing an alias, you can use it in code to represent the aliased class. For example:

Visual C#

// You can now refer to MyNameSpaceTwo as myAlias. The // following two lines produce the same result: MyNameSpaceTwo.Widget anotherWidget = new MyNameSpaceTwo.Widget() ; myAlias anotherWidget = new myAlias() ;

You cannot create aliases for types in this manner in Visual Basic .NET.

Referencing External Libraries

You might want to use class libraries not contained by the .NET Framework, such as libraries developed by third-party vendors or libraries you developed. To access these external libraries, you must create a reference.

To create a reference to an external library

  1. In the Solution Explorer, right-click the References node of your project.

  2. From the pop-up menu, choose Add Reference. The Add Reference dialog box appears.

  3. Choose the appropriate tab for the library you want to reference. .NET libraries are available on the .NET tab. Legacy COM libraries appear on the COM tab, and local Visual Studio projects appear on the Projects tab.

  4. Locate the library you want to reference, and double-click it to add it to the Selected components box. Click OK to confirm the choice of that reference.

Lesson Summary

  • The .NET Framework base class library is a library of code that exposes functionality useful for application building. The base class library is organized into namespaces, which contain types and additional namespaces related to common functionality.

  • Types can be either value types or reference types. A variable of a value type contains all the data associated with that type. A variable of a reference type contains a pointer to an instance of an object of that type.

  • Non-user-defined value types are created on declaration and remain empty until they are assigned a value. Reference types must be instantiated after declaration to create the object. Declaration and instantiation can be combined into a single step without any loss of performance.

  • When a value type variable is assigned to another value type variable, the data contained within the first variable is copied into the second. When a reference type variable is assigned to another reference type variable, only the reference to the object is copied, and both variables will refer to the same object.

  • You can use the using or Imports statements to allow references to members of a namespace without using the fully qualified name. If you want to use an external library, you must create a reference to it.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

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