|< Day Day Up >|
A namespace is a name that is used to organize related types within an assembly or across assemblies. For example, all the .NET Framework types are collected in the System namespace. All the .NET Framework types that relate to Windows Forms are collected into the System.Windows.Forms namespace, and so on. Namespaces are open in that multiple declarations can contribute to the same namespace ”even across multiple assemblies. In the following example, both namespace declarations contribute to the same namespace, so the MegaCorp.Controls namespace contains both Button and Label .
Namespace MegaCorp.Controls Class Button ... End Class End Namespace Namespace MegaCorp.Controls Class Label ... End Class End Namespace
It is sometimes necessary to use the full name of the type when referring to it in code. The full name of a type includes the type's namespace ”for example, MegaCorp.Controls.Button . This can become onerous, however, if the namespace is long and the type is frequently used. The Imports statement allows referring to a type without the need to include its namespace.
Imports MegaCorp.Controls Module Test Sub Main() Dim x As Button = New Button() ... End Sub End Module
If the same type name exists in two different imported namespaces, it is not possible for the compiler to know which type the name refers to. The Imports statement can also be used to define an alias for a type or a namespace to allow disambiguation in this situation. In this example, the Button type is defined in both the MegaCorp.Controls namespace and the TinyCorp.Controls namespace. When the namespaces are imported, aliases are assigned to each namespace so that the code can make it clear which Button it is referring to.
Imports Mega = MegaCorp.Controls Imports Tiny = TinyCorp.Controls Namespace MegaCorp.Controls Class Button ... End Class End Namespace Namespace TinyCorp.Controls Class Button ... End Class End Namespace Module Test Sub Main() Dim x As Mega.Button Dim y As Tiny.Button ... End Sub End Module
The members of a type can also be imported using Imports . For instance, this can be used to refer to the names of enumerations without qualification.
Imports Color Enum Color Red Green Blue End Enum Module Test Sub Main() Dim c As Color = Red End Sub End Module
|< Day Day Up >|