In this tutorial, we will discuss the uses and benefits of namespaces and classes in VB.NET. Much like most object-oriented programming languages namespaces and classes are used to organize processes in large web applications. We will cover how to create and use namespaces and classes.
In general, namespaces are equivalent to groups. Namespaces can also be nested meaning one can be placed inside of another namespace. A good example of this is when you use the Imports (VB.NET) or Using (C#) to use classes, structures, etc. for Regular Expressions, SQL Database Manipulation, or File Management. All of these elements are organized with namespaces to prevent loading unnecessary elements during each web request.

First you can start a new Web Application in Visual Studio 2008. Add the ASP.NET App_Code folder to your Web Application. Now add a new class file. Depending on whether you are in Visual Basic or C# mode, the file’s extension will be vb or cs. Now we will add a namespace and a class inside of that namespace.

Now that we have created this class inside of this namespace, we will have to learn how to call it. This class won’t be accessible by the application unless it called by the namespace or included at the beginning of the application. We will show an example below.

Either method is correct and comes down to personal preference. Depending on how many times you will be referencing the class, you may want to include the namespace instead of attaching it to the class name every time it is needed. If there were another namespace called Namespace2 nested inside of Namespace1 with the Class1 class located inside of it, then you would reference the class with Namespace1.Namespace2.Class1.

Now we can test out our new class by adding some code to it. We are going to create a public sub called MsgBox2. This sub is going to send a message box to the user. Here is an example.

In order to access the sub we will need to import the namespace. Next I have declared the theClass variable as class Class1 inside of the Page_Load sub. Then we will call the MsgBox2 sub so that the user will be sent a message box when the page is first loaded. Below is an example.

Namespaces can hold several different elements such as classes, structures, interfaces, enumerations, and other namespaces. These will all be referenced with the same format as directed above.

Download Source Files