Posts

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: var SL : TStringList ; Value : Integer ; begin SL := 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: var SL : TStringList ; R1 , R2 : TRect ; PR : PRect ; Idx : Integer ; MyRect : TRect ; begin .. . // add some strings and objects SL := 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 t