Creating and Using Namespaces in visual basic.Net
Namespaces help you to create logical groups of related classes and interfaces.
Need for Namespace
NameSpaces allow us to organize Classes so that they can be easily accessed in other applications. Namespaces enable us to avoid any naming conflicts between classes that have the same name. We can use two classes with the same name in an application provided they belong to different namespaces.
How do you implement namespaces in a database application? What are the benefits of using namespaces in a database application? For all this read Database programming using visual basic, c# (c sharp) sql server.
For example, we create a new class named TextBox to accept only an integer type of value. However, if we want to use the VS.Net TextBox control in the same project, there will be a conflict in the name. When we create a Namespace, we will be able to easily distinguish between the Class TextBox created by us and the one provided by VS.Net.
Creating Namespaces in visual basic.Net
Every project in Visual Basic.Net has a root namespace, which is set in the Property page of the project. When we create a project, by default, the name of the root namespace for the project is set to the name of the new project. For example, the root namespace for a project named MyProject is MyProject. Usually, when we create a project, we would like to give it a name which we like.
So, we need to change the MyProject to the name which we wish. We will name the project as Acct1.
We can also organize classes using the Namespace keyword.
For example, you can create a user-defined namespace called EmpNamespace in the project called Acct1 and place the class EmpClass within the EmpNamespace block.
The fully qualified or proper usage of the class EmpClass will be:
The .Net framework uses a dot(.) as a delimiter between classes and namespaces.
Using Namespaces in visual basic.Net
We have created a Namespace in the previous step. Now, we will use the Namespace explicitly through direct addressing or implicitly through the Imports statement.
Direct addressing involves directly accessing any class in the namespace by providing the fully qualified name.
Example of using fully qualified name is given below:
Microsoft.VisualBasic.MsgBox("Using Fully Qualified Name")
If we want to make all the classes in a given namespace available without the need to type the entire namespace each time, you can use the Imports statement. An example of using the Imports statement is given below:
MsgBox("Using Imports Statement")
Similarly, in the example we have chosen:
Namespaces are of two types, Local and Global. Local Namespaces are accessible only to the applications to which they belong. Global Namespaces are accessible from all applications.
In this article we have learnt the need for a NameSpace, created one and used it in an example.