Thursday, June 19, 2014

Enumerating Controls the Easy Way

Yesterday I had to write a mapping from a set of radio buttons to an integer (and back). I couldn’t use TRadioGroup and so I had to iterate over controls to find out which one is checked. To do that, I used an enumeration helper which I wrote long time ago.

function TfrmColorRemappingDlg.GetMapping: integer;
var
ctrl:
TControl;
begin
Result := 0
;
for ctrl in EnumControls(Self, TRadioButton)
do
if TRadioButton(ctrl).Checked
then
Exit(ctrl.Tag);
end;

At that point I decided that this old-way enumeration is not good enough for the modern times. What I particularly dislike about it is that I know the type of objects enumerator will return (TRadioButton in this example) but I still have to cast the enumeration variable to that type. The solution is simple – use generics!