Showing posts from March, 2014

Been casting value types to stuff into TStrings.Objects[]?

On numerous occasions I've had the need to store simple, record and interface types in variable or fields of type TObject and had to use some horrible casting to do it. For example, you may resorted to doing stuff like this:varSL:TStringList;Value:Integer;beginSL:=TStringList.Create;Value:=42;SL.AddObject('some text',TObject(5));...end; Not nice!Things get worse when the size of the data type is greater than SizeOf(TObject) and this kind of horror is needed:varSL:TStringList;R1,R2:TRect;PR:PRect;Idx:Integer;MyRect:TRect;begin...// add some strings and objectsSL:=TStringList.Create;R1:=Rect(0,0,42,56);GetMem(PR,SizeOf(TRect));PR^:=R1;SL.AddObject('some text',TObject(PR));R2:=Rect(1,2,3,4);GetMem(PR,SizeOf(TRect));PR^:=R2;SL.AddObject('some more text',TObject(PR));...// do something with SL e.g.MyRect:=PRect(SL.Objects[0])^;...// free the allocated memoryforIdx:=0toPred(SL.Count)dobeginPR:=PRect(SL.Objects[Idx]);FreeMem(PR,