Information Technology Reference
In-Depth Information
Namespaces
In the MyWidgets example, since you have the source code, you can solve the name clash by just
changing the name of the SquareWidget class in either the SuperLib source code or the UltraLib
source code. But what if these libraries had been developed by separate companies, and you
didn't have the source code? Suppose that SuperLib was produced by a company called
MyCorp, and UltraLib was produced by the ABCCorp company. In that case, you wouldn't be
able to use them together if you used any classes or types where there was a clash.
As you can imagine, with your development machine containing assemblies produced by
dozens of different companies, there is likely to be a certain amount of duplication in the
names of classes. It would be a shame if you couldn't use two assemblies in the same program
just because they happened to have type names in common. The namespace feature helps you
avoid this problem.
Namespaces group a set of types together and give them a name, called the namespace
name . The namespace name should be descriptive of the contents of the namespace and be
distinctive from other namespace names.
The following shows the syntax for declaring a namespace. The names of all the classes
and other types declared between the curly braces are members of the namespace.
Keyword Namespace name
namespace SimpleNamespace
{
TypeDeclarations
}
Now suppose that the programmers at MyCorp have modified the source code as shown
in the following example. It now has a namespace that surrounds the class declarations. Notice
two interesting things about the namespace name:
￿
The company name is at the beginning of the namespace name.
￿
Namespaces can contain periods.
Company name Period
namespace MyCorp.SuperLib
{
public class SquareWidget
{
public double SideLength = 0;
public double Area
{
get { return SideLength * SideLength; }
}
}
}
Search WWH ::




Custom Search