[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 447
  • Last Modified:

implicit typecasting

Hi

I have created a new type TMyType. Now I want to have a random number of this type in a list, array, etc.

I first used a TObjectList, which worked fine, but I got some ugly code, because I had to typecast to my type the whole time.
Like this (ObjectList[i] as TMyType).SomeProperty

I could use an array to make the code a bit nicer, but as I add and remove objects an array won't do.

Is it possible to create an ObjectList that works with TMyType.
It would be perfect if something like templates from C++ were around.
0
bnz
Asked:
bnz
1 Solution
 
TOndrejCommented:
You can derive your own TMyTypeList from TList to hold TMyType type elements just as TObjectList does for TObject type elements...
0
 
ITugayCommented:
Hi bnz,

here is a short sample how to create list to keep your objects

  // your object
   TMyType = class(TObject)
     Name: String;
   ...
   end;

  // list that keeps your objects
  TMyTypes = class(TObjectList)
  private
      function GetItem(Index: Integer): TMyType;
  public
     property Items[Index: Integer] read GetItem; defsult;
  end;

implementation

function TMyTypes.GetItem(Index: Integer): TMyType;
begin
  Result := TMyType(Inherited Items[Index]);
end;

......
var
  MList: TMyTypes;
......
  MList[10].Name := 'Some name';
 
-------
Igor.  
0
 
AvonWyssCommented:
Another way to do implicit typecasts instead of explicit ones it to use a normal TList and to have a temporary variable of TMyType. Since TList deals with generic pointers, you can assign them to and from a TMyType variable without typecast, thus making Delphi do an invisible typecast.
0
 
DMNCommented:
Also it's possible to use TCollection and TCollectionItem
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now