Namespaces

Namespaces help you organize the objects in an assembly, such as classes, interfaces, structures, enumerations, and other namespaces.

Using namespaces helps you avoid problems such as naming collisions or conflicts within your code. For example, let's say you have a class named Math that contains functionality to add or subtract the value of Excel ranges. You could add a reference to an assembly that contains a class also named Math but having different functionality. When you run your application, there would be no way for the .NET Framework to distinguish between your Math class and the referenced Math class.

Creating namespaces for your classes gives you another level of naming that helps disambiguate your classes. In the same way that using people's last names can help distinguish them from others who share the same first name, using a namespace along with a class name (also known as fully qualifying a class) helps the .NET Framework runtime distinguish one class from a like-named class. Often a company name is used as an alias of a namespace, so, for example, MyCompany.Employees can be easily distinguished from YourCompany.Employees.

To fully qualify the name of an object, you simply prefix the object with the namespace. For example, the Button class that you add to a Word document is in the Microsoft.Office.Tools.Word.Controls namespace and is referenced as Microsoft.Office.Tools.Word.Controls.Button. In contrast, the Button class you add to a Windows Form is in the System.Windows.Forms namespace and is referenced as System.Windows.Forms.Button.

You can include a namespace in your project by using the Imports statement, and you can optionally provide an alias to be used in place of the namespace. For example, you could add the following line to the top of your code file:

Imports Microsoft.Office.Tools.Word

Or, to disambiguate this namespace from the Microsoft.Office.Interop.Word namespace, you might use an alias:

Imports Tools = Microsoft.Office.Tools.Word

In this way, you can refer to an object within that namespace by using the alias. So instead of declaring myBookmark as a Microsoft.Office.Tools.Word.Bookmark, you could declare it as a Tools.Bookmark.

0 0

Post a comment