Monday, September 17, 2007

DN4DP#13: Overloaded default array properties

It's been a while now, but this post continues the series of The Delphi Language Chapter teasers from Jon Shemitz’ .NET 2.0 for Delphi Programmers book.

What a good time to continue this series just after the major Delphi for .NET 2.0 launch, CodeGear RAD Studio 2007!

The previous post covered the exotic topic of Record Helpers. Today we'll look at another exotic-ish topic - overloaded default array properties.

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.

"Overloaded default array properties

A class or component can have an array property that is declared as default. This mechanism has now been extended to allow multiple overloaded default array properties - as long as the number or types of indexer parameters are different.

TMyObject = class
property Items[Index: integer]: string read GetItems write SetItems; default;
property Items[const Name: string]: string read GetNamedItems write SetNamedItems; default;

This means that you can use the array indexing syntax on the object instance - effectively overloading the array subscript operator [].

procedure Test; 
MyObject: TMyObject;
MyObject := TMyObject.Create;
MyObject[42] := 'The Answer';
MyObject['Bar'] := 'Yes';



HeartWare said...

Is this working for both Win32 and .NET or only for .NET?

Anonymous said...

It works in Delphi 2007 Win32 R2, haven't tested .Net though.
Code completion doesn't seem to understand it but who cares! This owns, I've wanted this several times over the last few years. :)

Unknown said...

It also works in D2006.
But indeed, you have to trick codecompletion a bit

Hallvards New Blog said...

In general, the Delphi Language chapter in .Net for Delphi Programmers targets the lanugage supported in Delphi 2006.

Unless explicitly noted, the language features work in both Win32 and .NET.

Nyet said...

Some years later... there's the issue of using overloaded array properties with BCB:

Copyright © 2004-2007 by Hallvard Vassbotn