Jasper Schellingerhout
Jasper Schellingerhout

Reputation: 1090

How can I get an enumeration's valid ranges using RTTI or TypeInfo in Delphi

I am using RTTI in a test project to evaluate enumeration values, most commonly properties on an object. If an enumeration is out of range I want to display text similar to what Evaluate/Modify IDE Window would show. Something like "(out of bound) 255".

The sample code below uses TypeInfo to display the problem with a value outside the enumeration as an Access Violation when using GetEnumName. Any solution using RTTI or TypeInfo would help me, I just don't know the enumerated type in my test code

program Project60;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,  TypInfo;

Type
  TestEnum = (TestEnumA, TestEnumB, TestEnumC);

const
  TestEnumUndefined = TestEnum(-1);

  procedure WriteEnum(const ATypeInfo: PTypeInfo; const AOrdinal: Integer);
  begin
    WriteLn(Format('Ordinal: %d = "%s"', [AOrdinal, GetEnumName(ATypeInfo, AOrdinal)]));
  end;


var
  TestEnumTypeInfo: PTypeInfo;
begin

  try
    TestEnumTypeInfo := TypeInfo(TestEnum);

    WriteEnum(TestEnumTypeInfo, Ord(TestEnumA));
    WriteEnum(TestEnumTypeInfo, Ord(TestEnumB));
    WriteEnum(TestEnumTypeInfo, Ord(TestEnumC));
    WriteEnum(TestEnumTypeInfo,  Ord(TestEnumUndefined));   //AV

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  ReadLn;
end.

Upvotes: 4

Views: 1195

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596497

Use GetTypeData() to get more detailed information from a PTypeInfo , eg:

procedure WriteEnum(const ATypeInfo: PTypeInfo; const AOrdinal: Integer);
var
  LTypeData: PTypeData;
begin
  LTypeData := GetTypeData(ATypeInfo);
  if (AOrdinal >= LTypeData.MinValue) and (AOrdinal <= LTypeData.MaxValue) then
    WriteLn(Format('Ordinal: %d = "%s"', [AOrdinal, GetEnumName(ATypeInfo, AOrdinal)]))
  else
    WriteLn(Format('Ordinal: %d (out of bound)', [AOrdinal]));
end;

Upvotes: 11

Related Questions