Type Casting a Record Structure as TObject.

1609 views
Skip to first unread message

Mark Harby

unread,
Nov 12, 2001, 11:28:00 AM11/12/01
to
Hello All

I need some help. I want to be able to type cast a record structure as a
TObject to allow me to add it as the object property of a TStringList.

eg.

type
TProductRecord = record
ProductCode : String;
Description : String;
QuantityIn : Double;
...
end;
var
ProductRecord : TProductRecord;
begin

MyList := TStringList.Create;
MyList.AddObject(IntToStr(ThisRecordNo), TObject(ProductRecord));


I get a ' (1170) Invalid typecast' error at the AddObject line when I try
and compile.
I know if I make the record a class instead it will work, but I don't want
it to be a class.

Any help gratefully received.


Mark Harby
FHM Consulting Limited
Nottingham. UK


Skybuck

unread,
Nov 14, 2001, 10:31:23 AM11/14/01
to
On Mon, 12 Nov 2001 16:28:00 -0000, "Mark Harby"
<mark....@nospam.virgin.net> wrote:

>Hello All
>
>I need some help. I want to be able to type cast a record structure as a
>TObject to allow me to add it as the object property of a TStringList.
>
>eg.
>
>type
>TProductRecord = record
> ProductCode : String;
> Description : String;
> QuantityIn : Double;
> ...
> end;
>var
> ProductRecord : TProductRecord;
>begin
>
> MyList := TStringList.Create;
> MyList.AddObject(IntToStr(ThisRecordNo), TObject(ProductRecord));

Try this:

MyList.AddObject(IntToStr(ThisRecordNo), TObject(@ProductRecord));

It compiles, not sure if it will work, you ll have to try it.

>I get a ' (1170) Invalid typecast' error at the AddObject line when I try
>and compile.
>I know if I make the record a class instead it will work, but I don't want
>it to be a class.
>
>Any help gratefully received.
>
>
>Mark Harby
>FHM Consulting Limited
>Nottingham. UK
>
>

--
Skybuck presents free software for windows 95 and up:
Network Info, UDP Speed Test and UDP Multicast Test
http://www.mycgiserver.com/~skybuck

Mark Harby

unread,
Nov 15, 2001, 6:19:37 PM11/15/01
to
Thanks for replying, yes it does compile but it doesn't work (at least I
can't get it to work when trying to retrieve the data). I have therefore
relented and doubled-up on my user-defined records and created classes as
well.

Ah well, really must read a good book on Delphi.

Mark Harby
Nottingham. UK


Andy Hill

unread,
Nov 16, 2001, 4:58:46 AM11/16/01
to
Did you typecast on the way back. As in:


type
PProductRecord = ^TProductRecord;


TProductRecord = record
ProductCode : String;
Description : String;
QuantityIn : Double;
...
end;
var
ProductRecord : TProductRecord;

Test: String;

begin
MyList := TStringList.Create;
MyList.AddObject(IntToStr(ThisRecordNo), TObject(@ProductRecord));
Test := PProductRecord(MyList.Objects[ThisRecordNo])^.ProductCode;

godsg...@gmail.com

unread,
Feb 25, 2016, 8:19:13 AM2/25/16
to
I was looking for the same thing and your Example worked - thanx :D
Reply all
Reply to author
Forward
0 new messages