As you saw earlier in this chapter, namespaces can expose objects that expose members. Moreover, namespaces can expose nested namespaces, which expose objects, and so on. You often need to access members of objects exposed by nested namespaces. To avoid needing to type the entire names of long (or nested) namespaces and write long lines of code, the Visual Basic language offers the Imports
directive. For example, consider the following lines of code that open a file on disk:
Dim myFile As New System.IO.FileStream("C: est.bin",
IO.FileMode.Open)
myFile.Close()
The FileStream
class is exposed by the IO
namespace, which is exposed by the System
namespace. You could place the following directive at the beginning of the code:
Imports System.IO
At this point, the first line of code could be rewritten as follows:
Dim myFile As New FileStream("C: est.bin", FileMode.Open)
Because you might be using long namespaces, Visual Basic offers a feature known as namespace aliasing, which allows you to define a custom identifier to represent the namespace. The following line demonstrates how to define a GZip
identifier to import the System.IO.Compression
namespace:
Imports GZip = System.IO.Compression
This is useful when you need to invoke members of the namespace in code, as in the following example:
'Instead of using System.IO.Compression.GZipStream,
'you can use a shortened format with namespace aliasing
Dim archive As GZip.GZipStream
Imports
directives are useful because they help make code much clearer. Just remember that such directives must be the first lines of each code file. The only exceptions are the Option
clause, which must precede the Imports
directives and, of course, comments.
3.15.214.155