The Delphi 8 compiler introduces the AUTOBOX directive. In the spirit of the Delphi Language Guide, I have presented information for the AUTOBOX directive in the table below.

Type SWITCH
Syntax {$AUTOBOX ON} or {$AUTOBOX OFF}
Default {$AUTOBOX OFF}
Scope Local

Remarks

The  $AUTOBOX directive controls the compatibility of simple types with other types.

In the {$AUTOBOX OFF} state, a simple type is compatible with only that simple type. In order for a simple type to be converted to another type, a boxing operation is needed.In order to remain compatible with previous versions of Delphi, this is the default.

In the {$AUTOBOX ON} state, a simple type is compatible with that simple type, and TObject itself. Also, in a call to a procedure with an interface type parameter, an object is compatible with only any interface types it implements, provided that the declared procedure is not overloaded.

Sample usage

var
 O: TObject;
 I: Integer;
begin
 I := 5;
 {$AUTOBOX ON}
  O := I;
 {$AUTOBOX OFF}
  O := TObject(I);
end.

Quiz time!

  1. What would happen if you remove the AUTOBOX ON directive? Why? Explain.
  2. What would happen if you remove the AUTOBOX OFF directive? Why? Explain.
  3. What would happen if you remove all the AUTOBOX directives? Why? Explain.

Which of the following code fragments would compile or not compile?

No Code fragment
1 {$AUTOBOX ON}
procedure Foo(Comparable: IComparable);
begin
end;

begin
Foo(42);
end.

2 {$AUTOBOX ON}
procedure Foo(Comparable: IComparable);
begin
end;

begin
Foo(TObject(42));
end.

3 {$AUTOBOX ON}
procedure Foo(Comparable: IComparable); overload;
begin
end;

begin
Foo(TObject(42));
end.