Namespaces
Namespaces organize the objects defined in an assembly. Assemblies can contain multiple namespaces, which can in turn contain other namespaces. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries.
The namespaces in the C1Zip assembly are:
• C1.C1Zip
• C1.C1Zip.ZLib
The following code fragment shows how to declare a C1ZipFile component using the fully qualified name for this class:
Dim zip As C1.C1Zip.C1ZipFile
• C#
C1.C1Zip.C1ZipFile zip;
Namespaces address a problem sometimes known as namespace pollution, in which the developer of a class library is hampered by the use of similar names in another library. These conflicts with existing components are sometimes called name collisions.
For example, if you create a new class named C1ZipFile, you can use it inside your project without qualification. However, the C1Zip assembly also implements a class called C1ZipFile. So, if you want to use the C1ZipFile class in the same project, you must use a fully qualified reference to make the reference unique. If the reference is not unique, Visual Studio .NET produces an error stating that the name is ambiguous. The following code snippet demonstrates how to declare these objects:
' Define a new C1ZipFile object (custom C1ZipFile class).
Dim MyC1ZipFile as C1ZipFile
' Define a new C1Zip.C1ZipFile object.
Dim ZipFile as C1.C1Zip.C1ZipFile
• C#
// Define a new C1ZipFile object (custom C1ZipFile class).
MyC1ZipFile as C1ZipFile;
// Define a new C1Zip.C1ZipFile object.
ZipFile as C1.C1Zip.C1ZipFile;
Fully qualified names are object references that are prefixed with the name of the namespace where the object is defined. You can use objects defined in other projects if you create a reference to the class (by choosing Add Reference from the Project menu) and then use the fully qualified name for the object in your code.
Fully qualified names prevent naming conflicts because the compiler can always determine which object is being used. However, the names themselves can get long and cumbersome. To get around this, you can use the Imports statement (using in C#) to define an alias — an abbreviated name you can use in place of a fully qualified name. For example, the following code snippet creates aliases for two fully qualified names, and uses these aliases to define two objects:
Imports C1File = C1.C1Zip.C1ZipFile
Imports MyFile = MyProject.C1ZipFile
Dim f1 As C1File
Dim f2 As MyFile
• C#
using C1File = C1.C1Zip.C1ZipFile;
using MyFile = MyProject.C1ZipFile;
C1File f1;
MyFile f2;
If you use the Imports statement without an alias, you can use all the names in that namespace without qualification provided they are unique to the project.
|