Search the Catalog
VB.NET Core Classes in a Nutshell

VB.NET Core Classes in a Nutshell

By Ted Neward, Budi Kurniawan
June 2002
0-596-00257-2, Order Number: 2572
574 pages, $44.95 US $69.95 CA

Chapter 1
Introduction

Contents:

Before the .NET FCL
The .NET Framework Class Library
Working with the .NET FCL
The Types of a .NET Namespace
Approaching the .NET FCL

The .NET Framework is Microsoft's new computing platform that simplifies the design, development, and deployment of computer applications. Developed particularly to facilitate the creation of Internet applications and distributed Internet applications, the .NET Framework features the .NET Framework Class Library (FCL), a systematic class framework to be used for the development of system tools and utilities as well as application software. This chapter assesses the significance of the .NET FCL and discusses accessing it from Visual Basic code.

Before the .NET FCL

Although programmers using languages like C++ have been using frameworks for system and application development from the very inception of their language (the Microsoft Foundation Class Library, or MFC, for instance, is a framework for developers of Windows applications using C++), comprehensive frameworks or class libraries are comparatively rare in Visual Basic programming. For the most part, programmers of previous versions of Visual Basic depended on two major sources to extend the Visual Basic language: the Win32 API, and ActiveX servers exposed through COM automation.

The Win32 API

The Win32 API is a procedural library that allows the developer to create programs that run under Windows and take advantage of core Windows operating system services. The Win32 API has been enhanced on a regular basis since it was introduced to support Windows NT 3.0, and it now consists of several thousand functions and constants located in a number of dynamic link libraries (DLLs). Because it is a loose collection of functions, there are'nt necessarily any consistent conventions in naming functions or in designating function parameters. The function-based style of programming using the Win32 API has a number of limitations:

Lack of consistency across the entire Win32 API

Although a collection of Win32 API functions may be interdependent, at the same time each function tends to be a more or less independent entity that is called in isolation from other functions in your program. This tends to make the Win32 API as a whole difficult for all programmers to learn and master.

Focus on C programmers

The Win32 API originally was developed as a set of functions that would be called primarily from C code. Although the Win32 API can be called from Visual Basic code, writing code that relies heavily on calls to external DLLs has always been something of an adventure in Visual Basic. Much of the challenge centers on the fact that the type systems used by C and Visual Basic are not completely compatible, so that Visual Basic data types have to be converted to data types expected by C language routines.

To get some sense of the difference in style between the function-based, procedural programming that characterizes the Win32 API and the object-oriented programming that characterizes the .NET Framework, Examples 1-1 and 1-2 contain the source code for a console mode routine that launches the application responsible for handling the data file whose name the user enters in a text box. Example 1-1 is written in Visual Basic 6.0 (although it could have run under any version from VB 4 through VB 6) and relies extensively on Win32 API calls, and particularly on calls to the registry API. Example 1-2 is written for Visual Basic .NET and relies on the .NET Framework Class Library, and particularly on its Registry and RegistryKey classes.

Example 1-1. Launching an application using the Win32 API

Option Explicit
  
Private Declare Function RegCloseKey Lib "advapi32.dll" ( _
        ByVal hKey As Long) As Long
Private Declare Function RegOpenKey Lib "advapi32.dll" _
        Alias "RegOpenKeyA" ( _
        ByVal hKey As Long, ByVal lpSubKey As String, _
        phkResult As Long) As Long
Public Declare Function RegQueryValue Lib "advapi32.dll" _
       Alias "RegQueryValueA" ( _
       ByVal hKey As Long, ByVal lpSubKey As String, _
       ByVal lpValue As String, lpcbValue As Long) As Long
Private Declare Function RegQueryValueEx Lib "advapi32.dll" _
       Alias "RegQueryValueExA" ( _
       ByVal hKey As Long, ByVal lpValueName As String, _
       ByVal lpReserved As Long, lpType As Long, _
       lpData As Any, lpcbData As Long) As Long
Public Declare Function WinExec Lib "kernel32" ( _
       ByVal lpCmdLine As String, ByVal nCmdShow As Long) _
       As Long
  
Public Const MAX_PATH = 260
  
Private Const HKEY_CLASSES_ROOT = &H80000000
  
Private Const ERROR_SUCCESS = 0&
  
Public Const REG_DWORD = 4
Public Const REG_SZ = 1
  
Public Const SW_SHOWNORMAL = 1
  
Private Sub Main()
   Dim strFile As String, strExten As String
   Dim strProgID As String, strExe As String
   Dim lPos As Long
   Dim hKey As Long, lStrLen As Long
  
   strFile = InputBox("Enter Name of File to Open: ", _
                      "Open File", "")
   If strFile = "" Then Exit Sub
  
   ' Get file extension
   lPos = InStrRev(1, strFile, ".")
   If lPos = 0 Then
      MsgBox "Filename must include an extension."
      Exit Sub
   Else
      strExten = Mid(strFile, lPos)
   End If
  
   ' Get programmatic identifier
   If RegOpenKey(HKEY_CLASSES_ROOT, strExten, hKey) <> _
                 ERROR_SUCCESS Then
      MsgBox "File extension not found."
      Exit Sub
   End If
   lStrLen = 0
   Call RegQueryValue(hKey, "", "", lStrLen)
   strProgID = Space(lStrLen)
   Call RegQueryValue(hKey, "", strProgID, lStrLen)
   RegCloseKey hKey
  
   ' Get associated application
   strProgID = Left(strProgID, lStrLen - 1) & _
               "\shell\open\command"
   If RegOpenKey(HKEY_CLASSES_ROOT, strProgID, hKey) <> _
                 ERROR_SUCCESS Then
      MsgBox "Open command key not found..."
      Exit Sub
   End If
  
   lStrLen = 0
   Call RegQueryValue(hKey, "", "", lStrLen)
   strExe = Space(lStrLen)
   Call RegQueryValue(hKey, "", strExe, lStrLen)
   RegCloseKey hKey
  
   ' Launch application and pass its filename as a parameter
   lPos = InStr(1, strExe, " %1")
   If lPos > 0 Then _
      strExe = Left(strExe, lPos)
   strExe = strExe & " " & strFile
   Call WinExec(strExe, SW_SHOWNORMAL)
End Sub

Example 1-1 is a relatively long program, largely because of the intricacies of working with the Win32 API. We need, of course, to declare all registry-related functions with their parameters, as well as all constants that we intend to use. In addition, each registry access requires that we do the following:

  1. Open the relevant registry key.

  2. Determine the length of the string we want to retrieve.

  3. Set the string buffer to the appropriate length.

  4. Retrieve the registry value.

  5. Adjust the string containing the registry value by removing its terminating null character.

  6. Close the open registry key.

In contrast, the VB.NET program in Example 1-2 is considerably shorter and simpler. In contrast to the numerous Declare and Const statements in Example 1-1, the program only needs to use the Imports statement to indicate which namespaces it will access. Registry access is also significantly simpler. The program relies on two classes: the shared Registry class, which provides access to HKEY_CLASSES_ROOT (HKCR), one of the top-level registry keys; and the RegistryKey class, which represents a registry key. As a result, once the program obtains a reference to HKEY_CLASSES_ROOT, registry access consists of the following steps:

  1. Open the appropriate subkey by calling the top-level key's open method, passing it the path to the subkey to be opened.

  2. Retrieve the newly opened key's default value.

  3. Close the open registry key.

Example 1-2. Launching an application using the .NET FCL

Option Strict On
  
Imports System
Imports Microsoft.Win32
Imports Microsoft.VisualBasic
  
Public Module modMain
   Public Sub Main()
      Dim strExten, strProgID, strExe As String
      Dim oProgID, oOpenCmd As RegistryKey
  
      Dim strFile As String = InputBox("Enter Name of File to Open: ", _
                                       "Open File", "")
      If strFile = "" Then Exit Sub
  
      ' Get file extension
      Dim iPos As Integer = InStrRev(strFile, ".")
      Try
         strExten = Mid(strFile, iPos)
      Catch
         MsgBox("Filename must include an extension.")
         Exit Sub
      End Try
  
      ' Get Programmatic Identifier
      Dim oHKCR As RegistryKey = Registry.ClassesRoot
      Try 
         oProgID = oHKCR.OpenSubkey(strExten)
         strProgID = CStr(oProgID.GetValue(Nothing))
         oProgID.Close()
      Catch
         MsgBox("File extension not found.")
         Exit Sub
      End Try
  
      ' Get associated application
      Try
         oOpenCmd = oHKCR.OpenSubkey(strProgID & _
                    "\shell\open\command")
         strExe = CStr(oOpenCmd.GetValue(Nothing))
         oOpenCmd.Close()
      Catch
         MsgBox("Open command key not found...")
         Exit Sub
      End Try
  
      ' Launch application and pass its filename as a parameter
      iPos = InStr(1, strExe, " %1")
      If iPos > 0 Then _
         strExe = Left(strExe, iPos)
      strExe = strExe & " " & strFile
  
      Call Shell(strExe, AppWinStyle.NormalFocus)
   End Sub
End Module

COM Automation

In place of the function-based programming using the Win32 API, COM automation represented a clear step forward. COM was a more or less object-oriented technology that held out the promise of language independence; as long as a language understood the Component Object Model, it should be able to access and take advantage of COM components.

Example 1-3 shows a VB 6 program written using COM automation that, like the programs in Examples 1-1 and 1-2, launches the application responsible for handling the data file whose name the user enters in a text box. Like the VB.NET program in Example 1-2, it is a short and fairly simple program that relies on the WScript object available from the Windows Script Host object model.

Example 1-3. Launching an application using COM automation

Option Explicit
  
Private Sub Main()
   On Error Resume Next
  
   Dim lPos As Long
   Dim strFile As String, strExten As String
   Dim strProgID As String, strExe As String
  
   strFile = InputBox("Enter Name of File to Open: ", _
                      "Open File", "")
   If strFile = "" Then Exit Sub
  
   ' Get file extension
   lPos = InStrRev(strFile, ".")
   If lPos = 0 Then
      MsgBox "Filename must include an extension."
      Exit Sub
   Else
      strExten = Mid(strFile, lPos)
   End If
  
   ' Initialize WSH Shell object
   Dim oShell As WshShell
   Set oShell = New WshShell
  
   ' Get programmatic identifier
   strProgID = oShell.RegRead("HKCR\" & strExten & "\")
   If Err.Number <> 0 Then
      MsgBox "File extension not found."
      Exit Sub
   End If
  
   ' Get associated application
   strProgID = "HKCR\" & strProgID & "\shell\open\command\"
   strExe = oShell.RegRead(strProgID)
   If Err.Number <> 0 Then
      MsgBox "Open command key not found..."
      Exit Sub
   End If
  
   ' Launch application and pass it filename as a parameter
   lPos = InStr(1, strExe, " %1")
   If lPos > 0 Then _
      strExe = Left(strExe, lPos)
   strExe = strExe & " " & strFile
  
   oShell.Run strExe, 5, True
End Sub

Despite its substantial popularity, COM suffered from a number of limitations:

In addition, COM did not offer an integrated class library comparable to the .NET FCL. Instead, the developers of each application or operating system service were free to implement whatever object model made sense to extend their application. As a result, there are major gaps in the functionality made available through COM automation, and there is not a good deal of consistency across object models.

The .NET platform and the .NET Framework Class Library were developed in an effort to address these weaknesses of COM.

The .NET Framework Class Library

The .NET Framework includes the .NET Framework Class Library (FCL), a vast collection of thousands of types (that is, of classes, interfaces, structures, delegates, and enumerations) that aim at encapsulating the functionality of core system and application services in order to make application programming easier and faster. There are classes that you can use to manipulate the file system, access databases, serialize objects, and launch and synchronize multiple threads of execution, to name just a few.

To make working with these classes easy, classes with similar functionality are grouped together in namespaces. Therefore, there is a namespace containing types for drawing, a number of namespaces for .NET remoting, etc. In fact, the "intrinsic" functions of the Visual Basic language (such as InStr, Len, and UBound) are implemented as class methods in the Microsoft.VisualBasic namespace. In total, the .NET FCL places more than 80 namespaces at your disposal.

The .NET FCL includes classes with the following functionality:

Data type definition

Some members of the System namespace, such as the Object, String, Int32, and Single classes, form the data types used by Visual Basic .NET (as well as by other .NET languages that rely on the .NET Common Type System).

Exceptions

When an exception is generated, the CLR provides exception information to the Exception class (in the System namespace) or to one of the derived classes found throughout the .NET FCL.

Events and event handlers

The signature of event handlers is represented by the EventHandler delegate (in the System namespace) or one of its derived delegates. The event information passed to an event handler is represented by the EventArgs class (in the System namespace) or one of its derived classes.

Attributes

Attributes allow custom items of information about a program element to be stored with an assembly's metadata. Since this information becomes a permanent part of the program element's description, it is always available and can be used to modify the design time, compile time, or runtime behavior of a program element. Attributes are classes derived from the Attribute class (in the System namespace) or one of its derived classes found throughout the .NET FCL.

Collections and data structures

The .NET FCL features a number of general-purpose and more specialized collection classes. The general-purpose classes include the Array class (in the System namespace) and the ArrayList and CollectionBase classes (in the System.Collection namespace). Specialized classes include the Stack class, a last-in, first-out structure, the Queue class, a first-in, first-out structure, in the System.Collection namespace, and the ListDictionary class, a linked list dictionary class, in the System.Collection.Specialized namespace.

Control creation

The .NET FCL provides full support for custom Windows and web controls that integrate with design-time environments like Visual Studio through a number of classes, including the Container class in the System.ComponentModel namespace or the CollectionEditor class in the System.ComponentModel.Design namespace.

Configuration settings

Using the .NET FCL, you have easy access to application configuration information from configuration files using classes such as AppSettingsReader and DictionarySectionHandler in the System.Configuration namespace. You can also access registry data using the Registry, RegistryHive, and RegistryKey classes in the Microsoft.Win32 namespace. Finally, you can access ActiveDirectory information using the members of the System.DirectoryServices namespace.

Debugging, profiling, and diagnostics

The .NET FCL makes a large number of debugging, diagnostic, and informational classes available that can help in locating and fixing bugs, as well as in improving overall performance. These include the Debug, Debugger, EventLog, and PerformanceCounter classes in the System.Diagnostics namespace.

Drawing

The FCL provides a full set of graphics objects, such as the Color structure, the Brush class, the Font class, and the Graphics class in the System.Drawing namespace.

Input/output

The FCL allows you to read the standard input, standard output, and standard error streams, as well as to access the file system, through classes like File, FileInfo, StreamReader, and StreamWriter in the System.IO namespace.

Availability of metadata

Through the Type class in the System namespace and classes like Assembly, Module, EventInfo, MethodInfo, and ParameterInfo in the System.Reflection namespace, the .NET FCL provides support for reading metadata (the data that describes particular program elements) at any time.

Remote calls

Through classes such as ObjRef, RemotingConfiguration, and RemotingServices in the System.Runtime.Remoting namespace, the .NET FCL adds support for remoting (calls that cross process or machine boundaries).

String handling and manipulation

Interestingly, in the .NET Framework, strings are immutable. This means that simple operations such as string concatenation involve an enormous performance penalty. The StringBuilder class in the System.Text namespace makes it possible to perform string concatenation efficiently. The RegEx and Match classes in System.Text.RegularExpressions make it possible to perform regular expression searches on strings.

Control of threading

In previous versions of Visual Basic, threading was a factor that enormously impacted VB applications but over which the VB developer had no control. With classes like Thread, Mutex, and Monitor in the System.Threading namespace, the .NET FCL for the first time places threading under the direct control of the VB.NET developer.

Data access

The .NET FCL features a brand new data access technology, ADO.NET. It is represented by classes like the DataSet class in the System.Data namespace, the OleDbConnection, OleDbCommand, and OleDbDataReader classes in the System.Data.OleDb namespace, and the SqlConnection, SqlCommand, and SqlDataReader classes in the System.Data.SqlClient namespace.

Windows desktop applications

The forms and controls that made Visual Basic the premier Rapid Application Development package for Windows have their equivalent in the .NET FCL. These classes, such as the Form class, the Button class, and the TextBox class, are found in the System.Windows.Forms namespace.

Web application development

In addition to Windows controls, the .NET FCL features two sets of controls for web application development. HTML server controls execute on the server but otherwise correspond more or less directly to standard client-side HTML controls. They are found in the System.Web.UI.HTMLControls namespace. Web controls (also known as ASP controls) are server controls that abstract the functionality of controls in a web application. They are found in the System.Web.UI.WebControls namespace.

Web services

A web service is simply a function call over the Internet. The .NET FCL supports the development of web services through the types in the System.Web.Services namespace.

As you can see, the functionality offered by the .NET FCL is extensive--and in this overview of the .NET FCL, we've only emphasized the highlights.

Working with the .NET FCL

Despite its vast size, the .NET FCL is a manageable collection of classes and their methods. This is because, unlike more traditional development tools such as the Win32 API, the .NET FCL is a collection of types (classes, interfaces, delegates, events, structures, modules, and enumerations) and their members organized into namespaces. A namespace is simply a logical grouping of classes that can in turn contain other namespaces, so that a collection of namespaces forms an inverse hierarchical tree. Organization of types into namespaces helps to prevent collisions in the event that types are identically named.

Although the .NET system of namespaces does not have a single root, we can consider the System namespace at the top of the .NET FCL hierarchy. It includes a wide variety of basic system classes, including data types, exception types, and types defining the most important attributes.

Defining Accessible Namespaces

The types in a namespace, in turn, reside in an assembly, which is simply a logical unit of deployment. An assembly provides the Microsoft Intermediate Language (MSIL) code for its contents, which is packaged in a Windows portable executable (PE) file. An assembly also specifies security permissions for itself, maintains a list of the types that it defines and their scopes, and specifies rules for resolving references to external types.

The assemblies in which namespaces of the .NET FCL reside are Windows dynamic link libraries (.DLLs). Typically, a single assembly contains multiple namespaces. In addition, however, a single namespace can reside in multiple assemblies. The System namespace, for example, resides in both mscorlib.dll and system.dll.

TIP: You can use ILDASM, the Intermediate Language disassembler included with the .NET Framework SDK, to see which namespaces and types are available in a particular assembly or DLL.

Namespaces are made available to Visual Studio or to the Visual Basic compiler by identifying the assembly in which the namespace resides. When using Visual Studio as the development environment for your Visual Basic projects, this is done by using the References dialog, as follows:

  1. Select Project Add Reference from the main menu, or right-click on References in the Solution Explorer window and select Add Reference from the popup menu.

  2. When the Add Reference dialog appears, make sure the .NET tab is selected, as shown in Figure 1-1. (The tab should be selected by default.)

  3. Select one or more DLL whose types you'd like to reference, then click the Select button. The assemblies you've added should appear in the Selected Components data grid. (See Figure 1-2.) Repeat this step if necessary until each assembly whose types you wish to access is displayed in the Selected Components data grid in the lower portion of the dialog.

  4. Click the OK button to close the dialog.

Figure 1-1

Figure 1-1. The .NET tab of the Add Reference dialog

WARNING: The Add Reference dialog does not list the assemblies whose references have already been added to a Visual Studio .NET project. You can see which assemblies are currently referenced by a project by expanding the References tree in the Solution Explorer window.

Figure 1-2

Figure 1-2. Selecting assemblies whose namespaces and types will be referenced

When compiling using the VB.NET command-line compiler, assemblies are made available to the compiler by using the /r: (or /reference:) compiler switch. Commas are used to separate DLLs if multiple DLLs are referenced. For example, the following command might compile a standard Windows desktop application:

vbc MyWinApp.vb /t:winexe /r:system.dll,system.windows.forms.dll

TIP: You may have noticed that you don't need to specify the path to .NET DLLs in order to access them. This is because they are registered in the Global Assembly Cache (or GAC), a location in which the Common Language Runtime expects to find its shared libraries.

References to some namespaces are added to every project created in the Visual Studio environment. The following are the project types supported by Visual Studio .NET, along with the .NET DLLs each project type automatically references:

ASP.NET web applications

System.dll

System.Data.dll

System.Drawing.dll

System.Web.dll

System.XML.dll

ASP.NET web services

System.dll

System.Data.dll

System.Web.dll

System.Web.Services.dll

System.XML.dll

Class libraries

System.dll

System.Data.dll

System.XML.dll

Console applications

System.dll

System.Data.dll

System.XML.dll

Web control libraries

System.dll

System.Data.dll

System.Drawing.dll

System.Management.dll

System.Web.dll

System.XML.dll

Windows applications

System.dll

System.Data.dll

System.Drawing.dll

System.Windows.Forms.dll

System.XML.dll

Windows control libraries

System.dll

System.Data.dll

System.Drawing.dll

System.Windows.Forms.dll

System.XML.dll

Windows services

System.dll

System.Data.dll

System.ServiceProcess.dll

System.XML.dll

All Visual Studio .NET projects written using Visual Basic also transparently reference two .NET DLLs: mscorlib.dll (which contains portions of the System namespace, as well as namespaces such as System.Collections, System.IO, System.Reflection, and System.Threading), and Microsoft.VisualBasic.dll (which defines the functions, procedures, constants, and attributes of the Visual Basic .NET language). The Visual Basic command-line compiler also references these two DLLs automatically, although it doesn't automatically reference any additional .NET assemblies.

Accessing Types in Namespaces

Once you've added a reference to an assembly, you can access any of the types in its namespaces by providing a fully qualified reference to the type. For instance, the code in Example 1-4 instantiates objects of the HashTable and DictionaryEntry classes, and also calls a method of the Console class.

Example 1-4. Using fully qualified namespace names

Option Strict On
  
Public Module modMain
   Public Sub Main
      ' Define hashtable
      Dim States As New System.Collections.HashTable()
      ' Add items
      States.Add("NY", "New York")
      States.Add("CA", "California")
      States.Add("MI", "Michigan")
      States.Add("VT", "Vermont")
      States.Add("WA", "Washington")
 
     ' Define and fill DictionaryEntry object
      Dim dict(States.Count - 1) As _
               System.Collections.DictionaryEntry
      Dim item As System.Collections.DictionaryEntry
      States.CopyTo(dict, 0)
  
      ' Iterate dictionary
      For Each Item in dict
         System.Console.WriteLine( _
            Microsoft.VisualBasic.Strings.UCase(CStr(item.Key)) _
            & ": " & CStr(item.Value))
      Next
   End Sub
End Module

In each case, the source code includes the fully qualified name of the type it instantiates or accesses; the Console class is a type in the System namespace, while the HashTable and DictionaryEntry classes are both types in the System.Collections namespace. Note that even the namespace of the supposedly "intrinsic" Visual Basic UCase function must be specified or a compiler error ("Name 'UCase' is not declared.") results if you attempt to compile the program using the Visual Basic command-line compiler. The UCase function, as you can see from the code in Example 1-4, is a member of the Strings class in the Microsoft.VisualBasic namespace.

Importing Namespaces

Needless to say, fully qualifying the name of each .NET type quickly becomes rather tiresome, particularly for types that are nested deep within a hierarchical namespace. You can, however, use the Imports directive to import a particular namespace, thereby allowing the compiler to resolve the reference to a particular type and eliminating the need for you to provide a fully qualified path to the type. For example, the code fragment shown in Example 1-4, when rewritten to use the Imports directive, appears as shown in Example 1-5 (new and modified lines of code appear in boldface).

Example 1-5. Importing namespaces with the Imports directive

Option Strict On
  
Imports SystemImports System.CollectionsPublic Module modMain
  
Public Sub Main
   ' Define hashtable
   Dim States As New HashTable()   ' Add items
   States.Add("NY", "New York")
   States.Add("CA", "California")
   States.Add("MI", "Michigan")
   States.Add("VT", "Vermont")
   States.Add("WA", "Washington")
  
   ' Define and fill DictionaryEntry object
   Dim dict(States.Count - 1) As DictionaryEntry   Dim item As DictionaryEntry   States.CopyTo(dict, 0)
  
   ' Iterate dictionary
   For Each Item in dict
      Console.WriteLine(CStr(item.Key) & ": " & _                        CStr(item.Value))   Next
End Sub
  
End Module

Note that while no namespaces are automatically imported by the command line compiler, Visual Studio automatically imports a number of namespaces, again depending on the project type. The project types and the namespaces that they automatically import are as follows:

ASP.NET web applications

Microsoft.VisualBasic

System

System.Collections

System.Configuration

System.Data

System.Drawing

System.Web

System.Web.UI

System.Web.UI.HTMLControls

System.Web.UI.WebControls

ASP.NET web services

Microsoft.VisualBasic

System

System.Collections

System.Data

System.Diagnostics

Class libraries

Microsoft.VisualBasic

System

System.Collections

System.Data

System.Diagnostics

Console applications

Microsoft.VisualBasic

System

System.Collections

System.Data

System.Diagnostics

Web control libraries

Microsoft.VisualBasic

System

System.Collections

System.Data

System.Diagnostics

System.Management

Windows applications

Microsoft.VisualBasic

System

System.Collections

System.Data

System.Diagnostics

System.Drawing

System.Windows.Forms

Windows control libraries

Microsoft.VisualBasic

System

System.Collections

System.Data

System.Diagnostics

System.Drawing

System.Windows.Forms

Windows services

Microsoft.VisualBasic

System

System.Collections

System.Data

System.Diagnostics

In addition, the AssemblyInfo.vb file automatically imports two additional namespaces, System.Reflection and System.Runtime.InteropServices, into every project.

You can have Visual Studio automatically import a particular namespace, which makes it available to all of the source code files in a project, as follows:

  1. Select Project Properties from the main menu, or right-click on the project name in the Solution Explorer window and select Properties from the popup menu to open the properties dialog.

  2. Select Common Properties Imports in the treeview control on the right to display the Imports property page.

  3. Enter the fully qualified name of the namespace you'd like to import in the Namespace dialog and click the Add Import button. Repeat this step for each namespace you'd like to automatically import in the project.

  4. Click OK to close the property page.

While the use of the Imports directive can save a substantial amount of typing, it does mean that the compiler is left to identify the namespace containing a particular type. This means that, if identically named types are found in the imported namespaces, Visual Basic will not be able to determine which type you wish to instantiate. For example, consider the code in Example 1-6, which defines two custom namespaces, each with a class named Person.

Example 1-6. Classes with the same name

Option Strict On
  
Namespace Extensions.Classes
  
   Public Class Person
      Dim sName As String
  
      Public Sub New(Name As String)
         sName = Name
      End Sub
  
      Public Property Name() As String
         Get
            Return sName
         End Get
         Set
            sName = Value
         End Set
      End Property
   End Class
End Namespace
  
Namespace Extensions.Demographics
   Public Enum Gender As Short
      Male = 2
      Female = 1
   End Enum
  
   Public Class Person
      Dim shAge As Short
      Dim chGender As Gender
  
      Public Property Age() As Short
         Get
            Return shAge
         End Get
         Set
            shAge = Value
         End Set
      End Property
  
      Public Property Gender() As Gender
         Get
            Return chGender
         End Get
         Set
            chGender = Value
         End Set
      End Property
   End Class
End Namespace

This code can be compiled into a dynamic link library. We can then attempt to access the Person class using code like that in Example 1-7.

Example 1-7. A type collision

Option Strict On
  
Imports Extensions.Classes
Imports Extensions.Demographics
Imports System
  
Module modMain
   Public Sub Main()
      Dim oPerson As New Person("John Doe")
      Console.WriteLine(oPerson.Name)
  
      Dim oPerson2 As New Person
      oPerson2.Age = 32
      oPerson2.Gender = Gender.Female
      Console.WriteLine(oPerson2.Gender.ToString)
   End Sub
End Module

However, when we attempt to compile this code, the VB.NET command-line compiler raises two instances of the following compiler error:

error BC30561: 'Person' is ambiguous, imported from the namespaces or types 'Extensions.Demographics, Extensions.Classes'.

To resolve this problem of type collisions, two solutions are available. The first is to use the fully qualified namespace name to indicate the namespace containing the type we want to instantiate, just as if we hadn't used the Imports statement. The second is to assign an alias to a namespace and to use that alias to identify the namespace containing the type we want to instantiate. To do this, we also use the Imports directive, which then has the following syntax:

Imports aliasname = namespace 

where aliasname is the alias by which the namespace will be referenced in code, and namespace is the fully qualified namespace name.

We can then modify our code example from Example 1-7 to take advantage of aliasing. The result is shown in Example 1-8 (again, modified lines are shown in boldface).

Example 1-8. Using aliasing to prevent type naming conflicts

Option Strict On
  
Imports cl = Extensions.ClassesImports Extensions.Demographics
Imports System
  
Module modMain
   Public Sub Main()
      Dim oPerson As New cl.Person("John Doe")      Console.WriteLine(oPerson.Name)
  
      Dim oPerson2 As New Person
      oPerson2.Age = 32
      oPerson2.Gender = Gender.Female
      Console.WriteLine(oPerson2.Gender.ToString)
   End Sub
End Module

Note that we have aliased a single namespace, which has magically resolved the ambiguous reference to both namespaces. The use of an alias, however, means that all further references to types in the Extensions.Classes namespace must use the alias in order to resolve the reference to the type, or we must use the fully qualified name of the type.

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

Approaching the .NET FCL

It may seem that, given both the newness and the enormity of the .NET platform, a substantial learning curve is required to "learn" the .NET FCL. In fact, this isn't the case; you can begin to take advantage of the class library immediately by selecting those classes, structures, and enumerations and their members that are of immediate interest to you and ignoring the rest. You can then gradually expand your familiarity with the .NET FCL as needed.

This incremental approach to learning the .NET FCL is possible because Visual Basic was written to run under the .NET platform, and much of the Visual Basic language (or at least the functions and procedures not implemented directly by the Visual Basic compiler) actually wrap functionality found in the .NET FCL.

The clearest example of this is to be found in the data types supported by Visual Basic. While Visual Basic's data types appear to be intrinsic, in fact they are defined by the .NET FCL; Visual Basic merely provides wrappers for each of the .NET data types for which it offers native support. This, in fact, is one of the major strengths of the .NET Framework: it features the Common Type System (CTS), which allows components and applications written in one .NET-compliant language to more or less seamlessly interoperate with components written in other .NET-compliant languages. Table 1-1 shows the "intrinsic" Visual Basic data types and their corresponding .NET FCL data types.

Table 1-1. VB.NET data types and their corresponding .NET FCL data types

VB.NET data type

.NET FCL data type

Boolean

System.Boolean

Byte

System.Byte

Char

System.Char

Date

System.DateTime

Decimal

System.Decimal

Double

System.Double

Integer

System.Int32

Long

System.Int64

Object

System.Object

Short

System.Int16

Single

System.Single

String

System.String

That the standard VB data types are merely wrappers for CTS data types is indicated by the Visual Basic SystemTypeName function, which returns the name of a CTS data type that corresponds to a particular "intrinsic" VB data type. For example, the code fragment:

Dim i as Integer = 12345
Dim s As String = "New World"
  
Console.WriteLine(SystemTypeName(TypeName(i)))
Console.WriteLine(SystemTypeName(TypeName(s)))

shows that the VB Integer corresponds to the .NET System.Int32 data type, while the VB String data type corresponds to the .NET System.String data type. In other words, we could also declare and initialize our two variables as follows:

Dim i as System.Int32 = 12345
Dim s As System.String = "New World"

The fact that VB data types are really CTS data types means that we can access the fields, properties, and methods of CTS datatypes from VB variables. Consider, for example, the following code fragment:

Dim d As Double
Dim b As Byte
Dim s As String = InputBox("Enter a number (0-255): ")
  
If IsNumeric(s) Then
   d = CDbl(s)
   If b.MaxValue >= d And b.MinValue <= d Then
      b = CByte(s)
   End If
   Console.WriteLine(TypeName(b) & " value: " & b)
End If

The code simply checks whether the numeric equivalent of a string entered by the user is within the range of the VB Byte data type by retrieving the values of the System.Byte data type's MinValue and MaxValue fields.

TIP: Because they don't exist in the Framework Class Library, two intrinsic data types found in previous versions of VB have been removed from the language. The first is the Currency data type. In its place, use the Decimal data type, which in the .NET platform is a standard data type. (In previous versions of VB, the Decimal was a subtype of the Variant data type, and variables could be cast as decimals only by calling the CDec conversion function.) The second is the Variant data type, which has been replaced by the Object data type as VB's "universal" data type.

Moreover, the reverse is also true: given a CTS data type, we can pass it as a parameter to methods that work on Visual Basic data types. For example:

Option Strict On
Imports Microsoft.VisualBasic
Imports System
  
Public Module modMain
  
Public Sub Main
   Dim iNum As Int32 = 1234
   Dim sNum As System.String = CStr(iNum)
  
   Console.WriteLine(Mid(sNum,3,2))
End Sub
  
End Module 

This code includes two instances of calls to VB.NET methods using CTS data types. The first is the call to the CStr conversion function, which is passed a variable of type Int32. The second is the call to the Mid string manipulation function, which is passed a variable of type System.String.

This means that, when working with Visual Basic data types, you can continue to call intrinsic Visual Basic functions, and call the members of .NET data types when they provide important functionality not available directly from Visual Basic. The following sections detail some of those functions.

Array Class

Just as Visual Basic scalar data types are in fact CTS scalar data types, so Visual Basic arrays are actually members of the .NET System.Array class. Some of its members that are not readily available in Visual Basic .NET are shown in the following table:

Name

Member type

Description

BinarySearch

Shared method

Searches a one-dimensional array for a particular value

Clear

Shared method

Sets a range of array elements to zero, False, or a null reference, depending on the members' data type

Copy

Shared method

Copies a portion of one array to another and performs any necessary type conversions

CopyTo

Method

Copies all the elements of a one-dimensional array to another one-dimensional array starting at a particular index position

IndexOf

Shared method

Returns the index of the first occurrence of a particular value in an array

IsFixedSize

Property

Returns a Boolean indicating whether an Array object has a fixed size

IsReadOnly

Property

Returns a Boolean indicating whether the elements in Array object are read-only

LastIndexOf

Shared method

Returns the index of the last occurrence of a particular value in an array

Rank

Property

Returns an Integer indicating the number of dimensions of the array

Reverse

Shared method

Reverses the elements in all or part of a one-dimensional array

Sort

Shared method

Sorts a one-dimensional array

Boolean Structure

The following table lists the members of the System.Boolean structure that are not readily available in the Visual Basic .NET language:

Name

Member type

Description

FalseString

Shared field

Returns the string representation of the Boolean value False. This is a read-only constant value.

Parse

Shared method

Converts a string (whose value must be either Boolean.TrueString or Boolean.FalseString) to its Boolean equivalent.

TrueString

Shared field

Returns the string representation of the Boolean value True. This is a read-only constant value.

Byte Structure

The Visual Basic .NET Byte data type is synonymous with the .NET System.Byte data type. The following table lists some of the members of the Byte class that are not readily available in Visual Basic:

Name

Member type

Description

MaxValue

Shared field

A constant representing the largest possible value of an instance of the Byte class

MinValue

Shared field

A constant representing the smallest possible value of an instance of the Byte class

Parse

Shared method

Converts the numeric representation of a string to its Byte equivalent

Char Structure

Char, a new data type in VB.NET, corresponds to the System.Char data type. Some of the members of the latter that offer functionality not available in VB.NET are shown in the following table:

Name

Member type

Description

GetUnicodeCategory

Shared method

Returns a member of the UnicodeCategory enumeration (in the System.Globalization namespace) indicating the character type of a Char object.

IsControl

Shared method

Returns a Boolean indicating whether a particular Unicode character is a control character.

IsDigit

Shared method

Returns a Boolean indicating whether a particular Unicode character is a decimal digit. (The decimal and thousands separators are not considered digits.)

IsLetter

Shared method

Returns a Boolean indicating whether a particular Unicode character is a letter of the alphabet.

IsLetterOrDigit

Shared method

Returns a Boolean indicating whether a particular Unicode character is a digit or a letter of the alphabet.

IsLower

Shared method

Returns a Boolean indicating whether a particular Unicode character is a lowercase letter. The method returns True only for letters of the alphabet; that is, Char.IsLetter must also return True.

IsNumber

Shared method

Returns a Boolean indicating whether a particular Unicode character is a decimal or hexadecimal digit.

IsPunctuation

Shared method

Returns a Boolean indicating whether a particular Unicode character is a punctuation mark.

IsSeparator

Shared method

Returns a Boolean indicating whether a particular Unicode character is a separator character (e.g., a space). The method does not return True if the character is a numeric separator.

IsSymbol

Shared method

Returns a Boolean indicating whether a particular Unicode character is a symbol.

IsUpper

Shared method

Returns a Boolean indicating whether a particular Unicode character is an uppercase letter. The method returns True only for letters of the alphabet; that is, Char.IsLetter must also return True.

IsWhiteSpace

Shared method

Returns a Boolean indicating whether a particular Unicode character is white space.

MaxValue

Shared field

A constant containing the largest possible value of Char object.

MinValue

Shared field

A constant containing the smallest possible value of a Char object.

Parse

Shared method

Converts a particular character in a string to a Char object.

DateTime Structure

The Visual Basic Date data type corresponds to the .NET Framework's DateTime structure. The following table lists the DateTime members whose functionality is not available in the date/time functions supported by the VB.NET language:

Name

Member type

Description

AddMilliseconds

Method

Adds a designated number of milliseconds to the DateTime instance

AddTicks

Method

Adds a designated number of ticks to the DateTime instance

CompareTo

Method

Compares the current DateTime instance to an object and returns an indication of their relative values

DaysInMonth

Shared method

Returns the number of days in a designated month and year

FromOADate

Shared method

Converts an OLE Automation Date value to a DateTime instance

GetDateTimeFormats

Method

Returns a String array containing all the string representations supported by the standard DateTime format specifiers

IsLeapYear

Shared method

Returns a Boolean indicating whether a particular year is a leap year

MaxValue

Shared field

A constant containing the largest possible value of a DateTime instance

Millisecond

Property

Retrieves the milliseconds component of a DateTime instance

MinValue

Shared field

A constant containing the smallest possible value of a DateTime instance

Now

Shared property

Returns the current local date and time

Parse

Shared method

Converts a string representation of a date/time to a DateTime instance

ParseExact

Shared method

Converts a string representation of a date/time in a specified format to its DateTime equivalent

Ticks

Property

Returns a Long containing the number of ticks that represent the date and time value of this instance

TimeOfDay

Property

Returns the current time of day

Today

Shared property

Returns the current date

ToFileTime

Method

Converts the DateTime instance to the format of the local system's file time

ToLocalTime

Method

Converts the current coordinated universal time (UTC) to local time

ToLongDateString

Method

Converts a DateTime instance to its long date string representation

ToLongTimeString

Method

Converts a DateTime instance to its long time string representation

ToOADate

Method

Converts the value of this instance to a Double representing the OLE Automation date

ToShortDateString

Method

Converts a DateTime instance to its short date string representation

ToShortTimeString

Method

Converts a DateTime instance to its short time string representation

ToUniversalTime

Method

Converts the value of the DateTime instance to coordinated universal time (UTC)

UtcNow

Shared property

Returns a DateTime instance that represents the current local date and time expressed as the coordinated universal time (UTC)

Decimal Structure

The VB.NET Decimal data type corresponds directly to the System.Decimal structure. The CTS Decimal structure includes the following members whose functionality is not readily available in VB.NET:

Name

Member type

Description

FromOACurrency

Shared method

Converts a Long containing an OLE Automation Currency value (e.g., a VB6 or VBScript Currency value) to a Decimal value

GetBits

Shared method

Converts a particular Decimal value to its binary representation and returns that value as an Integer

MaxValue

Shared field

A constant containing the largest possible value of a Decimal object

MinValue

Shared field

A constant containing the smallest possible value of a Decimal object

ToOACurrency

Shared method

Converts a Decimal value to an OLE Automation Currency value (e.g., a VB6 or VBScript Currency value), which it returns as a Long

Double Structure

The VB.NET Double data type corresponds to the .NET Framework's System.Double data type. The following table lists the members of the latter that offer functionality not found in the Visual Basic .NET language:

Name

Member type

Description

Epsilon

Shared field

A constant containing the smallest positive Double value greater than zero

MaxValue

Shared field

A constant containing the largest possible value of a Double object

MinValue

Shared field

A constant containing the smallest possible value of a Double object

NaN

Shared field

A constant containing the representation of a value that is not a number (NaN)

NegativeInfinity

Shared field

A constant containing a number that represents negative infinity

PositiveInfinity

Shared field

A constant containing a number that represents positive infinity

IsInfinity

Shared method

Returns a Boolean indicating whether the value of a Double object represents positive or negative infinity

InNaN

Shared method

Returns a Boolean indicating whether a Double object contains a value that is not a number (NaN)

IsNegativeInfinity

Shared method

Returns a Boolean indicating whether the value of a Double object represents negative infinity

IsPositiveInfinity

Shared method

Returns a Boolean indicating whether the value of a Double object represents positive infinity

Parse

Shared method

Converts the string representation of a number to its Double equivalent

Int16 Structure

The VB.NET Short data type corresponds directly to the System.Int16 structure. The members of the latter structure that offer unique functionality are shown in the following table:

Name

Member type

Description

MaxValue

Shared field

A constant containing the largest possible value of an Int16 object

MinValue

Shared field

A constant containing the smallest possible value of an Int16 object

Parse

Shared method

Converts the string representation of a number to its Int16 equivalent

Int32 Structure

The VB.NET Integer data type corresponds directly to the System.Int32 structure. The members of the Int32 structure that offer unique functionality are shown in the following table:

Name

Member type

Description

MaxValue

Shared field

A constant containing the largest possible value of an Int32 object

MinValue

Shared field

A constant containing the smallest possible value of an Int32 object

Parse

Shared method

Converts the string representation of a number to its Int32 equivalent

Int64 Structure

The VB.NET Long data type corresponds directly to the System.Int64 structure. The members of the Int64 structure that offer unique functionality are shown in the following table:

Name

Member type

Description

MaxValue

Shared field

A constant containing the largest possible value of an Int64 object

MinValue

Shared field

A constant containing the smallest possible value of an Int64 object

Parse

Shared method

Converts the string representation of a number to its Int64 equivalent

Object Class

The VB.NET Object data type corresponds to the System.Object class. System.Object, however, offers no functionality that is not available through the standard Visual Basic language.

Single Structure

The VB.NET Single data type corresponds to the .NET Framework's System.Single data type. The following table lists the members of the latter that offer functionality not found in the Visual Basic .NET language:

Name

Member type

Description

Epsilon

Shared field

A constant containing the smallest positive Single value greater than zero

MaxValue

Shared field

A constant containing the largest possible value of a Single object

MinValue

Shared field

A constant containing the smallest possible value of a Single object

NaN

Shared field

A constant containing the representation of a value that is not a number (NaN)

NegativeInfinity

Shared field

A constant containing a number that represents negative infinity

PositiveInfinity

Shared field

A constant containing a number that represents positive infinity

IsInfinity

Shared method

Returns a Boolean indicating whether the value of a Single object represents positive or negative infinity

InNaN

Shared method

Returns a Boolean indicating whether a Single object contains a value that is not a number (NaN)

IsNegativeInfinity

Shared method

Returns a Boolean indicating whether the value of a Single object represents negative infinity

IsPositiveInfinity

Shared method

Returns a Boolean indicating whether the value of a Single object represents positive infinity

Parse

Shared method

Converts the string representation of a number to its Single equivalent

String Class

The VB.NET String data type is equivalent to the System.String class. The members of the String class that offer functionality not incorporated in the VB.NET language are shown in the following table:

Name

Member type

Description

Chars

Property

Returns a Char instance representing the character at a particular position in a string

Clone

Method

Returns an additional reference to a particular String instance

CompareOrdinal

Shared method

Compares two strings without considering locale settings

CopyTo

Method

Copies a designated number of characters starting at a particular position in a string to a character array

Empty

Shared field

A constant representing an empty string

EndsWith

Method

Returns a Boolean indicating whether the String instance ends with the substring passed to the method as an argument

Format

Shared method

Replaces each format specification in a string with its corresponding value

IndexOf

Method

Returns the position of the first occurrence of a character or a substring within the string instance

IndexOfAny

Method

Returns the index of the first occurrence in this String instance of any element in a character array

Insert

Method

Inserts a substring at a designated position of a String instance

LastIndexOf

Method

Returns the position of the last occurrence of a designated character or substring within the string instance

LastIndexOfAny

Method

Returns the position of the last occurrence in this String instance of any of a set of characters in a character array

PadLeft

Method

Right aligns the characters in a String instance by padding them with a space or another designated character

PadRight

Method

Left aligns the characters in a String instance by padding them with a space or another designated character

Remove

Method

Deletes a specified number of characters from a String instance beginning at a designated position

StartsWith

Method

Returns a Boolean indicating whether the String instance begins with a designated substring or character

ToCharArray

Method

Copies the characters in the String instance to a Unicode character array

Non-CTS Data Types

Note, however, that because they are not part of the Common Language Specification (the specification that defines the core functionality that a .NET platform must implement), VB does not wrap the following CTS data types:

System.SByte

Description: Signed byte

Value Range: -128 to 127

System.UInt16

Description: Unsigned 16-bit integer

Value Range: 0 to 65,535

System.UInt32

Description: Unsigned 32-bit integer

Value Range: 0 to 4,294,967,295

System.UInt64

Description: Unsigned 64-bit integer

Value Range: 0 to 18,446,744,073,709,551,615

Back to: VB.NET Core Classes in a Nutshell


oreilly.com Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies | Privacy Policy

© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com