Type aliases

[next] [prev] [prev-tail] [tail] [up]

### 3.8 Type aliases

Type aliases are a way to give another name to a type, but can also be used to create real new types. Which of the two depends on the way the type alias is defined:

_________________________________________________________________________________________________________
Type aliases
___________________________________________________________________

The first case is just a means to give another name to a type:

Type
MyInteger = Integer;

This creates a new name to refer to the Integer type, but does not create an actual new type. That is, two variables:

Var
A : MyInteger;
B : Integer;

Will actually have the same type from the point of view of the compiler (namely: Integer).

The above presents a way to make types platform independent, by only using the alias types, and then defining these types for each platform individually. Any programmer who then uses these custom types doesn’t have to worry about the underlying type size: it is opaque to him. It also allows to use shortcut names for fully qualified type names. e. g. define system.longint as Olongint and then redefine longint.

The alias is frequently seen to re-expose a type:

Unit A;
Interface
Uses B;
Type
MyType = B.MyType;

This construction is often seen after some refactoring, when moving some declarations from unit A to unit B, to preserve backwards compatibility of the interface of unit A.

The second case is slightly more subtle:

Type
MyInteger = Type Integer;

This not only creates a new name to refer to the Integer type, but actually creates a new type. That is, two variables:

Var
A : MyInteger;
B : Integer;

Will not have the same type from the point of view of the compiler. However, these two types will be assignment compatible. That means that an assignment

A:=B;

will work.

The difference can be seen when examining type information:

If TypeInfo(MyInteger)<>TypeInfo(Integer) then
Writeln('MyInteger and Integer are different types');

The compiler function TypeInfo returns a pointer to the type information in the binary. Since the two types MyInteger and Integer are different, they will generate different type information blocks, and the pointers will differ.

There are three consequences of having different types:

1. That they have different typeinfo, hence different RTTI (Run-Time Type Information).
2. They can be used in function overloads, that is
   Procedure MyProc(A : MyInteger); overload;
   Procedure MyProc(A : Integer); overload;

   will work. This will not work with a simple type alias.

3. They can be used in operator overloads, that is
   Operator +(A,B : MyInteger) : MyInteger;

   will work too.

[next] [prev] [prev-tail] [front] [up]