2.1. Use the My Objects to Program Common TasksThe new My objects provide easy access to various features that developers often need but don't necessarily know where to find in the sprawling .NET class library. Essentially, the My objects offer one-stop shopping, with access to everything from the Windows registry to the current network connection. Best of all, the My object hierarchy is organized according to use and is easy to navigate using Visual Studio IntelliSense. 2.1.1. How do I do that?There are seven first-level My objects. Out of these, three core objects centralize functionality from the .NET Framework and provide computer information. These include: Note: Tired of hunting through the extensive . NET class library in search of what you need? With the new My objects, you can quickly find some of the most useful features . NET has to offer.
Along with these three objects, there are another two objects that provide default instances. Default instances are objects that .NET creates automatically for certain types of classes defined in your application. They include:
Finally, there are two other My objects that provide easy access to the configuration settings and resources:
Warning: Note that the My objects are influenced by the project type. For example, when creating a web or console application, you won't be able to use My.Forms. Some of the My classes are defined in the Microsoft.VisualBasic.MyServices namespace, while others, such as the classes used for the My.Settings and My.Resources objects, are created dynamically by Visual Studio 2005 when you modify application settings and add resources to the current project. To try out the My object, you can use Visual Studio IntelliSense. Just type My, followed by a period, and take a look at the available objects, as shown in Figure 2-1. You can choose one and press the period again to step down another level. Figure 2-1. Browsing the My objectsTo try a simple example that displays some basic information using the My object, create a new console project. Then, add this code to the Main( ) routine: Console.WriteLine(My.Computer.Name) Console.WriteLine(My.Computer.Clock.LocalTime) Console.WriteLine(My.Application.CurrentDirectory) Console.WriteLine(My.User.Identity.Name) When you run this code, you'll see some output in the console window, which shows the computer name, current time, application directory, and user: SALESSERVER 2005-10-1 8:08:52 PM C:\Code\VBNotebook\1.07\MyTest\bin MATTHEW Warning: The My object also has a "dark side." Use of the My object makes it more difficult to share your solution with non-VB developers, because other languages, such as C#, don't have the same feature. 2.1.2. Where can I learn more?You can learn more about the My object and see examples by looking up the "My Object" index entry in the MSDN Help. You can also learn more by examining some of this book's other labs that use the My object. Some examples include:
|