Recipe 3.8. Using Namespaces


Problem

You want to place your classes within a specific .NET namespace.

Solution

Use the Namespace statement together with the default namespace identified in a project's properties.

Discussion

Every Visual Basic application resides within a default namespace, what we'll call the "absolute namespace position" for your application. Visual Studio automatically sets this to a top-level namespace with the same name as your project. For instance, if you just accept the default "WindowsApplication1" name for a new Windows Forms application, the namespace is also named WindowsApplication1. Since it's a top-level namespace, it resides at the same hierarchy position as the System namespace.

To alter the namespace for your project, open the Project Properties window, and change the "Root namespace" field on the Application tab. You can change it to use an existing namespace, such as System.Windows.Forms, but then you must take care to avoid naming conflicts with your classes.

When generating a full .NET application (EXE), your choice of namespace is not too problematic because that namespace exists only within the view of your program and its lifetime. Two applications using the WindowsApplication1 namespace will not conflict with each other. However, if you generate a .NET library (DLL) for general distribution to others outside your organization, you should select a namespace that will avoid conflicts with others. Microsoft recommends that you use a combination of your company name and the product name, as they did with the Microsoft.VisualBasic namespace.

Beyond the absolute namespace position, you can place your classes and other types in a "relative namespace position" within the larger default absolute namespace. When you add a class (or other type) to your project, it appears in the absolute namespace position:

 Class Class1 End Class 

If your project uses WindowsApplication1 as its absolute namespace, this class appears as WindowsApplication1.Class1. In relative positioning, you can insert a new namespace between the absolute position and the class:

 Namespace CoolClasses    Class Class1    End Class End Namespace 

Now, Class1 is fully referenced as WindowsApplication1.CoolClasses.Class1.

The Namespace keyword may include multiple namespace components (separated by periods), and you can nest them as well:

 Namespace CoolClasses    Namespace SomewhatCool.BarelyCool       Class Class1       End Class    End Namespace End Namespace 

This Class1 lives at WindowsApplication1.CoolClasses.SomewhatCool.BarelyCool.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net