Namespaces in Delphi.Net

I initially found the use of namespaces in Delphi.Net to somewhat confusing. I think the reason for this was the project Default Namepsace property. Although using the default namespace provides a nice short hand way of assigning all units in your project to the same namespace, it makes the naming of the units and source files a bit confusing, at least to me.

In Delphi.Net the namespace that a unit belongs to is determined by the name given on the unit statement. For example, Essentials.Esbase would put the unit EsBase into the Essentials namespace. Normally, the source file name must match the name given on the unit statement. So in the previous example, the source file name would be Essentials.EsBase.pas and the dcuil file would be Essentials.EsBase.dcuil.

This changes a bit when you use the project’s Default Namespace property. You set this property on the Directories/Conditionals page of the Project Options dialog. Once you set this property all source files in your project now belong to the default namespace. This means that you no longer need to specify the namespace as part of the source file name or in the unit name either as far as I can tell. Where I got myself into trouble was by explicitly specifying the default namespace when creating a unit. This put me into a situation where the Delphi IDE was telling me that the unit name didn’t match the source file name, even though, to my mind, they obviously did match. After all they were Essentials.EsBase.pas and Essentials.EsBase respectively. It turns out that if you give the default namespace in the unit name you must omit it from the source file name. So a source file name of EsBase.pas and a unit name of Essentials.EsBase works just fine. Just to add a bit more to the confusion, even though your source file name doesn’t include the namespace the dcuil file still does. So, in this example my unit name is Essentials.EsBase, my source file is EsBase.pas and my dcuil file is Essentials.EsBase.dcuil.

When working with packages, the confusion gets even worse because the dcpil file will be created with the default namespace but the assembly (DLL) will not.  You must specify the name space on the project name specifically if you want the DLL to have the namespace as a prefix.  If your dcpil and DLL file names do not match you will have major headaches when you try to use the new component in an application.  Everything will seem to be working perfectly until you try to compile the application.  At this point the IDE will try to rebuild the package and it will fail with various misleading and frustration error messages.

In short, I am going to avoid the use of the Default Namespace parameter in the project options from now on.  It causes more problems than it solves.

Leave a Reply