Examples Delphi

Demonstrates how to convert an Eumerated Types to a string.
The following functions demonstrate how to convert an enumerated
type to a string and vice versa using GetEnumName and GetEnumValue.
These functions need to be re-created for each enumerated type by
changing the function name and parameter types.
You will need to include TypInfo.pas in the uses clause.
(* For demo purposes creating a dummy type *)
type
TSuit = (Hearts, Diamonds, Clubs, Spades);
function SuitToString(Suit: TSuit): string;
begin
Result := GetEnumName(TypeInfo(TSuit), Ord(Suit));
end;
function StringToSuit(Suit: string): TSuit;
begin
Result := TSuit(GetEnumValue(TypeInfo(TSuit), Suit));
end;
(* This function will convert an existing Delphi type *)
function PositionToString(Position: TPosition): string;
begin
Result := GetEnumName(TypeInfo(TPosition), Ord(Position));
end;
To use the function(*DS*)s above drop a TButton onto a form and
add the following code to its OnClick event handler. This will
show a series of messagebox(*DS*)s with converted types as strings.
procedure TForm1.Button1Click(Sender: TObject);
var
s: TSuit;
begin
s := Hearts;
ShowMessage(SuitToString(s));
s := Diamonds;
ShowMessage(SuitToString(s));
s := Clubs;
ShowMessage(SuitToString(s));
s := Spades;
ShowMessage(SuitToString(s));
s := StringtoSuit((*DS*)Hearts(*DS*));
ShowMessage(SuitToString(s));
ShowMessage(PositionToString(Position));
end;