Imports Statement (Imports Alias)Place an Imports Statement at the start of a program to access the specified type or namespace.
This page was last reviewed on Jan 14, 2024.
Imports. Most larger VB.NET programs begin with an Imports Statement, and this is done to allow the program to more easily access types within namespaces.
With an equals sign, we can define an alias to a type or namespace. So we can use custom identifiers as types—this can make programs easier to read, or (more often) harder to read.
Example. This program uses 3 Imports statements. The first 2 statements are alias statements, meaning they import a type (a Class) and use a new word to refer to it.
Warning Using the word "Cat" to refer to StringBuilder is probably not a good idea. And neither is using Door to refer to Console.
Also We imports the RegularExpressions namespace directly, which gives us access to the Regex class.
Imports Cat = System.Text.StringBuilder Imports Door = System.Console Imports System.Text.RegularExpressions Module Module1 Sub Main() ' Create a StringBuilder using the Cat alias. Dim sparky As Cat = New Cat() sparky.Append("123") sparky.Append("abc") ' Use the Door alias to System.Console. Door.WriteLine(sparky) ' See if the Cat matches the Regex. If Regex.IsMatch(sparky.ToString(), "\d\d\d...") Door.WriteLine("OK") End If End Sub End Module
123abc OK
Using notes. Suppose you have a larger project with 2 classes both named with a common word. With Imports aliases, we could alias one of them to a slightly different word.
And This would allow the program to compile. It is probably best to use String2 instead of something unusual like Cat.
Summary. The Imports keyword is used to access namespaces or types like Classes. It cannot specify a method name—this will cause a compile-time error.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 14, 2024 (new).
© 2007-2024 Sam Allen.