| 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. 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. If you attempt to use an object in your program without a Reference, the line of code generates an error. 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 ... and are both correct. But ... 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.) |
|||||

