Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an alias for a referenced namespace

In C# one can add an "alias" to a reference. For example

using xyz = Microsoft.Office.Interop.Excel;

and then in code one could simply refer to the class as xyz.Method

Can one do something similar in the Delphi uses clause? eg.

//This is just an example
uses
  System.IOUtils As xyz;

The reason for asking is that both System.IOUtils & FMX.Objects contain TPath which means that one needs to type out the full namespace if both classes are used. It would be useful to simply have an alias name.

like image 660
Brendan Avatar asked Sep 06 '25 02:09

Brendan


2 Answers

As far as I know, you can define unit aliases only in Project Options. This you can set if you open it through the menu Project / Options (or simply by pressing CTRL + SHIFT + F11) and there on the first page you can specify unit aliases to the Unit aliases collection for the selected target build configuration in the format alias=namespace.unit like shown on this picture:

enter image description here

like image 70
TLama Avatar answered Sep 07 '25 15:09

TLama


If you want to create an alias for a type (and not for all the namespace), you can use the following code (I wrote it to explain your situation)

uses
  System.IOUtils, FMX.Objects;

procedure TForm1.FormCreate(Sender: TObject);
type
  TIOPath = System.IOUtils.TPath;
  TFMXPath = FMX.Objects.TPath;
var
  FMXPath: TFMXPath;
begin
  ShowMessage(TIOPath.GetExtension('sample.txt'));
  FMXPath := TFMXPath.Create(self);
  try
    // Use the FMXPath
  finally
    FMXPath.Free;
  end;
end;

The aliased types can be declared in a common unit and included everywhere you need it.

like image 20
Daniele Teti Avatar answered Sep 07 '25 15:09

Daniele Teti