RAD Studio (Common)
ContentsIndex
PreviousUpNext
Autoboxing (Delphi for .NET)
Type  
Switch  
Syntax  
{$AUTOBOX ON}, {$AUTOBOX OFF}  
Default  
{$AUTOBOX OFF}  
Scope  
Local  

Remarks 

The $AUTOBOX directive controls whether value types are automatically “boxed” into reference types. 

The following code will not compile by default; the compiler halts with a message that I and Obj have incompatible types.

var
    I: Integer;
    Obj: TObject;
begin
    I:=5;
    Obj:=I; // compilation error
end.

Inserting {$AUTOBOX ON} anywhere before the offending line will remove the error, so this code compiles:

var
    I: Integer;
    Obj: TObject;
begin
    I:=5;
    {$AUTOBOX ON}
    Obj:=I; // I is autoboxed into a TObject
end.

Reference types can not be automatically “unboxed” into value types, so a typecast is required to turn the TObject into an Integer:

var
    I: Integer;
    Obj: TObject;
begin
    I:=5;
    {$AUTOBOX ON}
    Obj:=I; // OK   
    // I:=Obj; // Can't automatically unbox; compilation error
    I:=Integer(Obj); // this works
end.

Turning on autoboxing can be convenient, but it makes Delphi less type safe, so it can be dangerous. With autoboxing, some errors that would otherwise be caught during compilation may cause problems at runtime. Boxing values into object references also consumes additional memory and degrades execution performance. With {$AUTOBOX ON}, you run the risk of not realizing how much of this data conversion is happening silently in your code. {$AUTOBOX OFF} is recommended for improved type checking and faster runtime execution. 

The $AUTOBOX directive has no effect in Delphi for Win32.

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!