ONDotNet.com    
 Published on ONDotNet.com (http://www.ondotnet.com/)
 See this if you're having trouble printing code examples


O'Reilly Book Excerpts: VB.NET Core Classes in a Nutshell

An Introduction to the .NET FCL, Part 4

Related Reading

VB.NET Core Classes in a Nutshell
By Budi Kurniawan, Ted Neward

by Budi Kurniawan and Ted Neward

In part four in this five part series on the .NET FCL from VB.NET Core Classes in a Nutshell, learn the types of a .NET namespace.

The Types of a .NET Namespace

Once you've made a namespace accessible to your code, you can access any of the types it contains. In this section, we'll survey the types that a .NET namespace can contain.

Classes

In VB.NET, classes are reference types; that is, when you create an instance of a class in code, you work with a pointer (or reference) to the object rather than with the object itself. This is similar to previous versions of Visual Basic.

When a .NET class is instantiated, its constructor (or its New subroutine) executes. Each .NET class can have one or more constructors (that is, constructors can be overloaded), and the constructor can either be parameterless or parameterized. Visual Basic .NET provides three ways to initialize a variable and invoke its constructor. These are illustrated in the following three sets of statements, each of which instantiates a System.IO.FileInfo object:

' Single statement
Dim oFile As New FileInfo("c:\documents\notes.txt") 
  
' Single Statement with separate call to constructor
Dim oFile As FileInfo = New FileInfo( _
    "c:\documents\notes.txt")
  
' Separate declaration and initialization
Dim oFile As FileInfo
oFile = New FileInfo("c:\documents\notes.txt")

Once we create an instance of a class, we can invoke its properties and methods. In addition, we can handle its events (assuming that it exposes events) if we instantiate the object using the WithEvents keyword. For example:

Dim WithEvents cn As New SqlConnection()

Visual Basic .NET, unlike previous versions of Visual Basic, supports both instance and shared members. Instance members exist for each instance of a class; in previous versions of Visual Basic, all members of a class were instance members. Shared members are members that are not associated with a specific instance of a class or a structure, but rather are common to all instances of a class. Accessing a shared member of a class does not require that the class be instantiated; it can be accessed using the class name only. In addition, if the shared member is a property, it has a single value for all instances of the class.

In Example 1-8, we accessed the shared WriteLine method of the Console class, as follows:

Console.WriteLine(oPerson.Name)

Note that, to do this, we didn't have to instantiate an instance of the Console class; we simply called the Console class directly. A peculiarity of Visual Basic is that you can invoke shared members using either the class name or the name of an instance variable. The following code fragment, which does create an instance of the Console class, also works:

Dim con As Console
con.WriteLine(oPerson2.Gender.ToString)

Structures

Structures are very similar to classes, except that they are value types rather than reference types. Most of the primitive data types (Boolean, Byte, Char, Int16, Int32, etc.) defined in the FCL are implemented as structures. Because structures don't support parameterless constructors, you don't use the New keyword to instantiate them.

You work with structures just as you work with .NET classes, except that the New keyword is not used in declaring a structure:

' Declaration and initialization
Dim num1 As Int16 = 10
  
' Separate declaration and initialization
Dim num2 As Int16
num2 = 10

Enumerations

An enumeration is a related set of constants. You don't have to instantiate enumerations to take advantage of their members. When working with enumerations in .NET, however, you must specify the name of the enumeration in order to access one of its constants. For example:

Dim dy As String = WeekdayName(1, False, _
    FirstDayOfWeek.Sunday)

Interfaces

Interfaces are virtual base classes; that is, they consist of members (methods, properties, and events) that have no implementation. Instead, derived classes must provide the implementation. For example, the following code fragment uses interface inheritance to define a new class:

Class CustomCompare
   Implements System.IComparable
  
   Public Function CompareTo(obj As Object) As Integer _ 
      Implements System.IComparable.CompareTo
      ' Implementation of IComparable.ICompareTo
   End Function
End Class

Delegates

A delegate is a reference type that represents a strongly typed function pointer. All delegates are explicitly or implicitly derived from the System.Delegate class, which includes a number of members that provide information about the delegate, create object instances, or invoke the delegate. Delegates can be used in event procedures, for asynchronous callbacks, and wherever the address of a function is expected. The following example uses a delegate to define the thread procedure to be passed to the ThreadPool class's QueueUserWorkItem method:

Option Strict On

      Imports Microsoft.VisualBasic
      Imports System
      Imports System.Threading
      Imports System.Windows.Forms

      Public Class ThreadedForm : Inherits Form

         Protected WithEvents btnStart As Button
         Protected lblOutput As Label

         Public Shared Sub Main()
            Dim thrdForm As New ThreadedForm()
            Application.Run(thrdForm)
         End Sub

         Public Sub New()

            Me.Height = 200
            Me.Width = 400

            btnStart = New Button()
            btnStart.Text = "&Start"
            btnStart.Top = 50
            btnStart.Left = 100
            btnStart.Width = 75
            btnStart.Height = 50
            Me.Controls.Add(btnStart)

            lblOutput = New Label()
            lblOutput.Top = 125
            lblOutput.Left = 100
            lblOutput.Width = 200
            lblOutput.Height = 75
            Me.Controls.Add(lblOutput)
            Me.Text = "Asynchronous Callback Example"
         End Sub

         Protected Sub btnStart_Click(sender As Object, _
                                      e As EventArgs) _
                       Handles btnStart.Click
            btnStart.Enabled = False
            Dim thrdProc As WaitCallback = AddressOf _
			    ThreadProcedure
            ThreadPool.QueueUserWorkItem(thrdProc, _ 
			    1000000)
         End Sub

         Protected Sub ThreadProcedure(o As Object)
            Dim i As Integer
            If TypeOf o Is Integer Then
               i = DirectCast(o, Integer)
            Else
               Exit Sub
            End If
            Dim lCtr As Long
            For lCtr = 0 to 10000000
               If lCtr Mod 1000000 = 0 Then
                  lblOutput.Text = lblOutput.Text & "X"
               End If
            Next
         End Sub

      End Class

In the next and final installment, learn the best approaches to the .NET FCL

Budi Kurniawan is a senior J2EE architect and author.

Ted Neward is an independent software development architect and mentor in the Sacramento, California area.

VB.NET Core Classes in a  Nutshell

Related Reading

VB.NET Core Classes in a Nutshell
By Budi Kurniawan, Ted Neward

Copyright © 2009 O'Reilly Media, Inc.