Search code examples
delphi

How to build enumerated Types with "classes"?


I have an enumerated type like Type1=(left,right,up,down) I usually have to build a function to convert this to a string for output.

case Type of
left: result:='left'
right: result:='right'
.
.
.
end

Is there any way I can do something like Type.toString while still having a simple assignment with Type:=left?


Solution

  • This can be done with a record helper, which despite its name works even for enumerations.

    type 
      Type1 = (left, right, up, down);
      Type1Helper = record helper for Type1
        function ToString: string;
      end; 
    
    
     function Type1Helper.ToString: string;
     begin
       case Self of
         left: result := 'left';
         right: result := 'right';
         up: result := 'up'; 
         down: result := 'down';
       end;
     end;