28

I know how to convert an enumerated type to an integer.

type
  TMyType = (mtFirst, mtSecond, mtThird); 

var 
  ordValue:integer;
  enumValue:TMyType;
...
ordValue:= Ord(mtSecond); // result is 1

But how do I do the inverse operation and convert an integer to an enumerated type?

menjaraz
  • 7,551
  • 4
  • 41
  • 81
lyborko
  • 2,571
  • 3
  • 26
  • 54
  • type TMyType = (mtFirst=1, mtSecond=2, mtThird=3); var ordValue:integer; enumValue:TMyType; ordValue:= Integer(mtSecond); // result is 2 – Engin Ardıç Oct 20 '13 at 15:41

3 Answers3

31

As Ken answered, you just cast it. But to make sure you have correct value you can use code like:

if (ordValue >= Ord(Low(TMyType))) and (ordValue <= Ord(High(TMyType))) then
    enunValue := TMyType(ordValue)
else 
    raise Exception.Create('ordValue out of TMyType range');
Daniel Grillo
  • 2,368
  • 4
  • 37
  • 62
ain
  • 22,394
  • 3
  • 54
  • 74
21

You can cast the integer by typecasting it to the enumerated type:

ordValue := Ord(mtSecond);
enumValue := TMyType(ordValue);
Ken White
  • 123,280
  • 14
  • 225
  • 444
7

Take care with casting because it requires full mapping with your ordinal type and integers. For example:

type Size = (Small = 2, Medium = 3, Huge = 10);
var sz: Size;
...
sz := Size(3); //means sz=Medium
sz := Size(7); //7 is in range but gives sz=outbound
NGLN
  • 43,011
  • 8
  • 105
  • 200
user3140262
  • 71
  • 1
  • 1