Import Namespaces to save Time and Write Less code

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 3.67 out of 5)
 

Importing Namespaces can save some time/typing when accessing its methods/properties/objects since you won’t have to refer to the actual namespace when using one of its members.


Example Below…

Without Importing


'Without Importing the Namespace...

MsgBox(System.IO.Directory.Exists("c:\"))

With Importing


'With the Namespace Imported...

MsgBox(Directory.Exists("c:\"))

The Importing example above saved time and code writing since you won’t have to include the System.IO. namespace every time you access one of its members. There are a couple ways you can import your Namespace. One way is adding the Imports statement with the Namespace just above where your Class begins and works for all .NET versions. Example…


Imports System.IO

Public Class frmMain

Inherits System.Windows.Forms.Form

'your code....

End Class

Another way is from the Projects Property page. To get to it simply go to the Project – Menu and click on your Projects – Properties Item which is usually the last item in the list.


Visual Basic.NET 2002/2003

Under “Common Properties” click on the “Imports” option. You will see a Namespace Textbox and a List of the currently Imported Namespaces. Simply type in the Namespace you want to add and click “Add Import”. Your Namespace will then be in the list and it is now “Imported” just as if you used the actual Imports statement.

Imports view for VB.NET.

Visual Basic 2005, Visual Basic 2008, and newer

For VB 2005 and VB 2008 adding Imports is under your Projects Properties page just like VB.NET 02/03. But it is under the “References” Tab. You will then see a list of References to the project and below that you will see the Imported Namespaces. Unlike VB.NET 02/03, there is actually a list of the common available Imports you can select. Just Check the Namespace you want to import and thats it. You can then use all of the Namespaces members and not have to include the namespace path which will save time and writing.

The VB 05/08 Imports view.


That’s all there is to it. Have Fun!

                Jason

Leave a Reply

Your email address will not be published.