< Day Day Up > |
Namespaces are very useful for organizing declarations, but as a practical matter, typing fully qualified names can get very tiresome. Having to type System in front of Console.WriteLine may be useful the first few times to understand where the type Console lives, but by the fiftieth or hundredth time (or thousandth time), you've probably gotten the point. To help this situation, a namespace or a type can be imported into a particular source file. Importing a namespace or type makes the members of that declaration available in that source file without qualification. For example: Imports System Module Test Sub Main() Console.WriteLine("Hello, world!") End Sub End Module The example imports the System namespace into the source file, so Console can be used without qualification.
In general, only namespaces are really useful to import, but importing a class can be useful in the case of an enumeration. Imports Colors Enum Colors Red Green Blue End Enum Module Test Sub Main() Dim c As Colors = Red If c = Blue Then ... End If End Sub End Module If a name is imported through two separate imports, attempting to use the name will result in an ambiguity error. In the following example, the name Test is ambiguous between namespace A and namespace B . Imports A Imports B Namespace A Class Test End Class End Namespace Namespace B Class Test End Class End Namespace Module TestModule Sub Main() Dim x As Test ' Error: Test is imported through A and B End Sub End Module To help resolve such ambiguities , an import can be assigned an alias . An alias is an alternate name given to the imported namespace or type and allows access to the members of the imported namespace or type through that alternate name. Using the previous example, we can resolve the ambiguity by assigning A.Text and B.Text aliases. Imports ATest = A.Test Imports BTest = B.Test Namespace A Class Test End Class End Namespace Namespace B Class Test End Class End Namespace Module TestModule Sub Main() Dim x As Test ' Error: Test is only imported through an alias Dim y As ATest Dim z As BTest End Sub End Module An import alias doesn't actually declare anything in the file, so it is possible to declare something else in the file with the same name as the import alias. However, the name of the alias must be unique in the top-level scope of the source file. |
< Day Day Up > |