The "My" Namespace
One of the shocks that VB6 programmers encountered when they migrate to Visual Basic .NET is the sheer number of class libraries available. VB6 programmers often struggle with finding the right class for the right task, and to them this task can be like finding a needle in a haystack.
To ease the pain of VB6 programmers, Microsoft has added the new My namespace in Visual Basic 2005.
The My namespace:
- Provides shortcuts to commonly used functionality within the .NET Framework
- Adds functionality that was previously difficult to find, difficult to use, or was simply not possible without unmanaged API calls
|Figure 1. My Namespace: The figure shows the objects in the My namespace.|
My includes the following objects (see Figure 1
For example, to get the computer to play a system sound, you can directly use the My.Computer object.
Contrast this to using the Win32 API to play audio, or using the Audio class within the Microsoft.VisualBasic.Devices namespace. (Who would have thought that this library was located in this namespace?)
Dim audio As New _
Another example of using the My namespace is downloading files from the Internet. The following statement downloads an image from the Web and then saves it onto your local drive:
In Visual Basic 2005, you can now split the definition of a class into multiple physical files using the new Partial
For example, you could rewrite the MyString class illustrated earlier as two separate partial classes (see Listing 2
|Note that in Visual Basic 2005, every partial class file except one from the complete set of partial class files that make up a class needs the Partial keyword.|
|Figure 2. Designer-generated Code: The designer-generated code for a Windows Form saved in a separate file.|
Using partial classes you can now try to separate a class definition into multiple files, perhaps one class for containing all the properties definitions and another class for all the methods. To the compiler, the partial classes are treated as one single class.
Partial classes are useful for separating designer-generated code and business logic. For example, in Visual Studio .NET 2003, the designer-generated code for a Windows Form is embedded within the code-behind for the form. This often creates a mess when developers unknowingly modify the generated code. In Visual Studio 2005, the designer-generated code for WinForms are all saved in a separate partial class (see Figure 2
), so your code behind for your Windows form is now clear of all the clutter (see Figure 3
|Figure 3. Code Behind: The figure shows the code behind of a Windows Form.|
Apart from using partial classes to separate business logic from UI, you can also use partial classes to add extra methods to classes that are auto generated, e.g., a typed dataset. You can then regenerate the auto generated part of the file without breaking the extra methods.