Jeff Cope
Jeff Cope

Reputation: 791

Record Helper & Class Methods

TTransactionType = (ttNone, ttCash, ttCheck, ttDebit);

TTransactionTypeHelper = record helper for TTransactionType
public
  class function ToTransactionType(TranTypeDescription : string) : TTransactionType;
  function ToString(): string;
end;

function TTransactionTypeHelper.ToString: string;
begin
  case Self of
    ttCash:
      Result := 'Cash';
    ttCheck:
      Result := 'Check';
    ttDebit:
      Result := 'Debit'
  else
    Result := '';
  end;
end;

class function TTransactionTypeHelper.ToTransactionType(
  TranTypeDescription: string): TTransactionType;
begin
  if (TranTypeDescription = 'Cash') then
    Result := ttCash
  else if (TranTypeDescription = 'Check') then
    Result := ttCheck
  else if (TranTypeDescription = 'Debit') then
    Result := ttDebit
  else
    Result := ttNone;
end;

The class method, ToTransactionType is accessible via TTransactionTypeHelper (expected).

Is there a way to make method ToTransactionType accessible via the enumeration directly? e.g.,

TTransactionType.ToTransactionType('Cash'); 

Upvotes: 1

Views: 784

Answers (1)

LU RD
LU RD

Reputation: 34899

As @Victoria mentions in a comment, adding static to the ToTransactionType method, will make the call TTransactionType.ToTransactionType('Cash') work just fine.

If you want to extend the enumeration type without writing a helper, that is not possible. But there is another way:

Using RTTI and unit TypInfo.Pas you could call GetEnumValue():

var
  i : Integer;
  myTransactionValue : TTransactionType;
begin
  i := GetEnumValue(TypeInfo(TTransactionType),'ttCheck');
  if (i <> -1) then myTransactionValue := TTransactionType(i);
end;

There is also GetEnumName():

s := GetEnumName(TypeInfo(TTransactionType),Ord(TTransactionType.ttCheck));  // s = 'ttCheck'

Upvotes: 2

Related Questions