Namespaces organize the objects defined in an assembly. Assemblies can contain multiple namespaces, which can in turn contain other namespaces. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries.
The general namespace for ComponentOne Windows products is C1.Win. The general namespace for ComponentOne Web-based products is C1.Web. The namespace for the C1Chart control is C1.Win.C1Chart, while the namespace for the wrapper assembly is C1.Web.C1WebChart. The following code fragment shows how to declare a C1Chart control using the fully qualified name for this class:
Dim chart As C1.Win.C1Chart.C1Chart
· C#
C1.Win.C1Chart.C1Chart chart;
· Delphi
chart: C1.Win.C1Chart.C1Chart;
Namespaces address a problem sometimes known as namespace pollution, in which the developer of a class library is hampered by the use of similar names in another library. These conflicts with existing components are sometimes called name collisions.
For example, if a new class named ChartLabels is created, it can be used inside the project without qualification. However, the C1Chart assembly also implements a class called ChartLabels. So, if the C1Chart class will be used in the same project, a fully qualified reference must be used to make the reference unique. If the reference is not unique, Visual Studio .NET produces an error stating that the name is ambiguous.
Fully qualified names are object references that are prefixed with the name of the namespace where the object is defined. Objects defined in other projects can be used if a reference to the class is created (by choosing Add Reference from the Project menu) and then using the fully qualified name for the object in the code.
Fully qualified names prevent naming conflicts because the compiler can always determine which object is being used. However, the names themselves can get long and cumbersome. To get around this, you can use the Imports statement (using in C#, uses in Delphi) to define an alias — an abbreviated name you can use in place of a fully qualified name. For example, the following code snippet creates aliases for two fully qualified names, and uses these aliases to define two objects:
Imports MyChart = C1.Win.C1Chart
Dim chart As
MyChart
· C#
using C1.Win.C1Chart = MyChart;
MyChart chart;
· Delphi
uses MyChart := C1.Win.C1Chart;
chart: MyChart;
If the Imports statement is used without an alias, use all the names in that namespace without qualification provided they are unique to the project.
As a warning, unless specified explicitly in the code, it is taken for granted that the following statement has been specified:
Imports C1.Win.C1Chart
· C#
using C1.Win.C1Chart;
· Delphi
uses C1.Win.C1Chart;
This applies only to small code samples. Tutorials and other longer samples will specify complete qualifiers.
Send comments about this topic to ComponentOne. Copyright © ComponentOne LLC. All rights reserved. |