Namespaces provide a way for a better organization of the code and avoiding conflicts between types with the same name. Consider a complex hierarchical framework of objects (such as .NET Framework) in which you have the need to expose more than one type with a particular identifier. The typical example is when software companies produce class libraries; different companies could have the need to provide their own implementation of the Person
class, or the same company could provide different implementations of the Person
class within the same assembly, so there could be ambiguities for developers when invoking a particular implementation of the Person
class. To solve this coding problem, programming languages in the .NET family offer the capability of organizing types within namespaces. For example, imagine using assemblies from two companies, Company1
and Company2
with both produced assemblies exposing their own implementation of the Person
class. You need to use one of the two implementations, but you still need to reference both assemblies in your project. The following code
Dim p As New Person
can cause the Visual Basic compiler to throw an exception because it does not know which of the two implementations you want to invoke. By using namespaces, you can avoid this ambiguity as follows:
Dim p1 As New Company1.Person
Dim p2 As New Company2.Person
In this code example, Company1
and Company2
are namespaces that virtually encapsulate lots of types whereas both Company1.Person
and Company2.Person
represent the full name of the Person
class. The .NET Framework Base Class Library highly relies on namespaces. The main namespace in the BCL is System
, which is basically the root in the BCL hierarchy. System
exposes dozens of other namespaces, such as System.Xml
, System.Data
, System.Linq
, and so on. Each of these namespace expose types and other nested namespaces, and in this way a hierarchical framework is more maintainable. Namespaces solve a coding problem and an object implementation problem. This is because namespaces are all about coding, because the Common Language Runtime does not recognize namespaces, whereas it does recognize only full class names, such as Company2.Person
in the previous example or System.Object
or System.Console
. Namespaces are just a logical feature that helps developers to write better organized and reusable code. Basically the CLR never encounters conflicts because it recognizes only full class names, but you learn later in this chapter that as a developer you may encounter such conflicts and a help in writing and organizing code is necessary, especially when working with long named classes (see the “Imports Directives” section).
18.119.116.43