Namespace
This is an organizational construct. It cannot be instantiated (as with New) like a Class
. Instead, we use a namespace to separate code into logical parts.
Namespace
benefitsNamespaces help developers understand code but do not impact execution. They can make a program easier to develop and learn.
This example program is divided into 3 classes. The first 2 classes use custom namespaces—Perls and Ruby. They both contain classes—two independent classes both named Website.
ProgramExample
. This contains the other namespaces.Namespace Perls Class Website Public Shared Sub Execute() Console.WriteLine("Perls Website") End Sub End Class End NamespaceNamespace Ruby Class Website Public Shared Sub Open() Console.WriteLine("Ruby Website") End Sub End Class End NamespaceImports ProgramExample.Perls Module Module1 Sub Main() ' This requires the Imports ProgramExample.Perls directive. Website.Execute() ' Access namespace directly in a statement. Ruby.Website.Open() End Sub End ModulePerls Website Ruby Website
There are many ways to use namespaces in programs. Every program by default uses a Root namespace. This is automatically generated when we create a new project.
Namespace
keyword.Namespace
, we use Imports or a direct access with a composite name (like Ruby.Website.Open
).Projects often have special rules for Namespaces. Many projects use company-based identifiers in Namespaces. Naming rules are specified by the project, not the VB.NET language itself.