Team Fly |
Page 11
its Sub New is executed automatically. Because constructors can accept arguments, the person who writes a class can specify which arguments, if any, are required (or optional, in the case of overloaded constructors).
Recall that you needn't use an Imports statement to use objects in the XML namespace or the data namespace. You do, however, need to use Imports with other namespaces, including quite commonly used ones such as System.IO. There appears to be no rational reason why certain assemblies are referenced by default, and others need to be imported. (One clue is perhaps that nearly any C code you look at always contains #include <stdio.h>, the standard I/O library.)
Beyond that, there is even a third class of assemblies that cannot be referenced by Imports. They are included in your projects by choosing Project Add Reference.
Another curiosity. You find one list of default assemblies in the References section of Solution Explorer, and a slightly different list of assemblies (including the Collections namespace) when you right-click the name of your project (it's boldface) in Solution Explorer, choose Properties from the context menu, then click the Imports option in the left pane of the Property Pages dialog box. You see that only some namespaces here duplicate those in Solution Explorer. What gives?
Earlier you saw how to use the GetDirectories method of the DirectoryInfo object to obtain a list of subdirectories:
Dim di As DirectoryInfo = New DirectoryInfo(''c:\") Dim dirs As DirectoryInfo() = di.GetDirectories()
Here's how you can use the Directory object to get a list of files. Notice that you use a string and string array here, rather than DirectoryInfo objects. Also, notice that the Directory object does not need to be instantiated at all:
Dim s As String() = Directory.GetFiles("c:\") Dim s1 As String For Each s1 In s Console.WriteLine(s1) Next
This is the information from the Object Browser, explaining that you need to assign the results of the GetFiles method to a string array:
Public Shared Function GetFiles(ByVal path As String) As String()
Experienced VB programmers are used to a finite set of variable data types (strings, objects, and a handful of numeric types). Now, in VB.NET, you must get accustomed to the fact that everything is an object. Further, some objects must be instantiated before they can be used (with the New statement), but other objects— viewed by the .NET designers as more "basic" objects, one assumes—do not need instantiation. The DirectoryInfo object does need instantiation; the Directory object does not.
Team Fly |