Cast Enumeration Value to Integer in Delphi

21,777

Solution 1

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. |

Solution 2

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.

Solution 3

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;
Share:
21,777
Shaun Roselt
Author by

Shaun Roselt

Software Developer (Delphi, Python, C#, SQL, HTML, CSS, Scratch). Potterhead.

Updated on July 09, 2022

Comments

  • Shaun Roselt
    Shaun Roselt almost 2 years

    Is it possible to cast/convert an Enumeration Value to Integer in Delphi?

    If yes, then how?