How do I convert an integer to an enumerated type?

lyborko picture lyborko · Jan 4, 2012 · Viewed 21.8k times · Source

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?

Answer

ain picture ain · Jan 4, 2012

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');