Tuesday, September 18, 2007

DN4DP#14: .NET platform support: Boxing

This post continues the series of The Delphi Language Chapter teasers from Jon Shemitz’ .NET 2.0 for Delphi Programmers book.

The previous post covered overloaded default array properties. The next few posts will be .NET specific - starting out with support for Boxing operations.

Note that I do not get any royalties from the book and I highly recommend that you get your own copy – for instance at Amazon.

".NET platform support

Custom features for a managed environment

Most of the language extensions we have discussed so far have been general in nature and applicable to both the .NET and Win32 platforms. In addition, Borland [now CodeGear - Ed.] has added new language features that map directly to intrinsics of the .NET platform. These make it easier for you to integrate with the FCL, external assemblies, the CLR and so on.

Boxing

As you know from Chapter 2 ["Just In Time Compilation" - Ed.], boxing is the process of converting a value type instance into a System.Object compatible reference, copying the value to the garbage-collected heap. By default in Delphi, boxing is an explicit operation involving a cast expression from the value type to System.Object (or the alias TObject).

While explicit boxing helps you identify spots where potentially expensive copy operations are going on, it can become bothersome in the long run. To enable implicit boxing operations (just like in C#), you can use the {$AUTOBOX ON} compiler directive.

Finally, the syntax to perform unboxing is identical with C# - just cast the TObject reference to the required value type. You can use the is operator to verify the actual value type held by the object reference.

procedure Test;
var
Collection: ArrayList;
O: TObject;
begin
Collection := ArrayList.Create;

{$AUTOBOX OFF}
Collection.Add(TObject(42));

{$AUTOBOX ON}
Collection.Add(84);

for O in Collection do
writeln(Byte(O));
end;


Note: When boxing integral constants, the compiler will box them as the smallest integral type that can hold it. If you want to box a constant as a specific type, you need to cast it or store it in a correctly typed variable first, like this Collection.Add(Integer(84)).

No comments:



Copyright © 2004-2007 by Hallvard Vassbotn