1. Home
  2. Computing & Technology
  3. Visual Basic
The VB.NET Imports Statement
Imports and References in VB.NET are often confused

The actual effect of the Imports statement in VB.NET is often a source of confusion for people just learning the language. And the interaction with VB.NET References makes for even more confusion. We're going to clear that up in this DYK article.

Here's the whole story very briefly ... then we'll go over the details in depth.

A Reference to a VB.NET namespace is a requirement and must be added to a project before the objects in the namespace can be used. The Imports statement is not a requirement and is simply a coding convenience that allows shorter names to be used.

Whew!

Now let's look at an actual example. To illustrate this idea, we're going to use the System.Data namespace - which provides the new ADO.NET data technology.

System.Data is added to Windows applications as a Reference by default in VB.NET.

System.Data Reference

Adding a namespace to the Reference collection in a project makes the objects in that namespace available to the project. The most visible effect of this is that the Visual Studio "Intellisense" helps you find the objects in popup menu boxes.

System.Data Reference

If you attempt to use an object in your program without a Reference, the line of code generates an error.

System.Data Reference

The Imports statement, on the other hand, is never required. The only thing it does is allow the name to be resolved without being fully qualified. In other words ...

Imports System.Data
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private Sub Form1_Load( ...
        Dim Test As OleDb.OleDbCommand
    End Sub
End Class

and

Imports System.Data.OleDb
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private Sub Form1_Load( ...
        Dim Test As OleDbCommand
    End Sub
End Class

are both correct. But ...

Imports System.Data
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private Sub Form1_Load( ...
        Dim Test As OleDbCommand
    End Sub
End Class

results in a syntax error ("Type 'OleDbCommand' is not defined") because the Imports namespace qualification System.Data doesn't provide enough information to find the object OleDbCommand.

Now that you know about References and the Imports statement, you might want to read this DYK Article about how References and Imports are really a coordinated hierarchy in VB.NET (But don't try it in C#! It doesn't work there.)

Explore Visual Basic

More from About.com

  1. Home
  2. Computing & Technology
  3. Visual Basic

©2008 About.com, a part of The New York Times Company.

All rights reserved.