A. This one comes up a lot. A reference allows your application to use logic that has been implemented in some external class library (a dll). If you want to use the classes in a particular library, you need to add a reference to that library so your application knows where to find those classes. In contrast, the "imports" statement is essentially a convenience feature. It tells your application which parts of all of the libraries you've referenced will actually be used. It does this by specifying the namespace in which those parts reside. Namespaces are a logical construct that exist solely to organize classes into hierarchical relationships, basically to make the 12,000+ classes in the .NET framework easier to get along with. It's important to note that you don't actually need to use the "imports" statement -- as long as a class is available within the project or via a reference, you can work with it via its fully-qualified name. For example:
' If I want to work with the SQLConnection object, I can import the namespace it lives in, like this...
imports system.data.sqlclient
' ...and then I've got the class available by name, and I can instantiate it:
dim myConn as new SQLConnection
' Alternately, I can skip the "imports" statement, and just refer to the class directly
dim myConn as new system.data.sqlclient.SQLConnection
' Both "dim" statements are semantically identical, and compile to the same MSIL code
Another reason for the use of namespaces is to avoid name collisions -- say, for example, that you implement your own SQLConnection class, inside of a namespace called "myNamespace". This is legal, because the fully-qualified names of the two classes are different, i.e.
' Microsoft class
dim msConn as new system.data.sqlclient.SQLConnection
' Your class
dim myConn as new myNamespace.SQLConnection
You can even import both namespaces and alias them for later use in distinguishing between class names:
imports TheMicrosoftOne = system.data.sqlclient
imports TheOtherOne = myNamespace
' This is the Microsoft one
dim msConn as new TheMicrosoftOne.SQLConnection
' This is the other one
dim myConn as new TheOtherOne.SQLConnection
So, in summary:- References tell your application where to find external code (i.e. in external dll's) that you want to use.- The "Imports" statement provides easy access to class names inside hierarchical namespaces.- You need references if you want to use classes from external libraries.- You do not need the "Imports" statement to use any given class, it is there to facilitate the organization of classes into namespaces. The "Imports" statement simply saves you some typing.
References: http://msdn2.microsoft.com/en-us/library/7f38zh8x.aspx
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment