Blow ThemUp
Blow ThemUp

Reputation: 905

enum from string

Given the following declarations below, is there a way to retrieve the enum value (e.g. jt_one) from a string value (e.g. 'one')?

type
 TJOBTYPEENUM =(jt_one, jt_two, jt_three);


CONST JOBTYPEStrings : ARRAY [jt_one..jt_three] OF STRING =
     ('one','two','three');

Or do i need to create my own function using a nested set of if statements?

NOTE: I am not looking for the string "jt_one"

Upvotes: 5

Views: 3698

Answers (2)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109158

function GetJobType(const S: string): TJOBTYPEENUM;
var
  i: integer;
begin
  for i := ord(low(TJOBTYPEENUM)) to ord(high(TJOBTYPEENUM)) do
    if JOBTYPEStrings[TJOBTYPEENUM(i)] = S then
      Exit(TJOBTYPEENUM(i));
  raise Exception.CreateFmt('Invalid job type: %s', [S]);
end;

or, neater,

function GetJobType(const S: string): TJOBTYPEENUM;
var
  i: TJOBTYPEENUM;
begin
  for i := low(TJOBTYPEENUM) to high(TJOBTYPEENUM) do
    if JOBTYPEStrings[i] = S then
      Exit(i);
  raise Exception.CreateFmt('Invalid job type: %s', [S]);
end;

Upvotes: 7

David Heffernan
David Heffernan

Reputation: 613572

function EnumFromString(const str: string): TJOBTYPEENUM;
begin
  for Result := low(Result) to high(Result) do 
    if JOBTYPEStrings[Result]=str then
      exit;
  raise Exception.CreateFmt('Enum %s not found', [str]);
end;

In real code you'd want to use your own exception class. And if you want to allow case insensitive matching, compare strings using SameText.

Upvotes: 10

Related Questions