Is it possible to cast/convert an Enumeration Value to an Integer in the Delphi Programming Language?
If yes, then how?
This is called out explicitly at the documentation for enumerated types:
Several predefined functions operate on ordinal values and type identifiers. The most important of them are summarized below.
| Function | Parameter | Return value | Remarks |
|---|---|---|---|
| Ord | Ordinal expression | Ordinality of expression's value | Does not take Int64 arguments. |
| Pred | Ordinal expression | Predecessor of expression's value | |
| Succ | Ordinal expression | Successor of expression's value | |
| High | Ordinal type identifier or variable of ordinal type | Highest value in type | Also operates on short-string types and arrays. |
| Low | Ordinal type identifier or variable of ordinal type | Lowest value in type | Also operates on short-string types and arrays. |
Ord(SomeEnumVariable) or Integer(SomeEnumVariable) ?Ord and so avoid a cast.Ord?I see David has posted you a good answer while I was writing this, but I'll post it anyway:
program enums; {$APPTYPE CONSOLE} uses SysUtils, typinfo; type TMyEnum = (One, Two, Three); var MyEnum : TMyEnum; begin MyEnum := Two; writeln(Ord(MyEnum)); // writes 1, because first element in enumeration is numbered zero MyEnum := TMyEnum(2); // Use TMyEnum as if it were a function Writeln (GetEnumName(TypeInfo(TMyEnum), Ord(MyEnum))); // Use RTTI to return the enum value's name readln; end. Casting the enum to an integer works. I could not comment on the other answers so posting this as an answer. Casting to an integer may be a bad idea (please comment if it is).
type TMyEnum = (zero, one, two); var i: integer; begin i := integer(two); // convert enum item to integer showmessage(inttostr(i)); // prints 2 end; Which may be similar to Ord(), but I am unsure which is the best practice. The above also works if you cast the enum to an integer
type TMyEnum = (zero, one, two); var MyEnum: TMyEnum; i: integer; begin MyEnum := two; i := integer(MyEnum); // convert enum to integer showmessage(inttostr(i)); // prints 2 end; ShowMessage(IntToStr(High(Ord(two)))) with ShowMessage(IntToStr(High(Integer(two)))).Ord(MyEnum) and Integer(MyEnum), I made an explicit question to @David. Pls see the comments of the David's answer.
Ord(myEnumValue).