Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Enumeration Value to Integer in Delphi

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

If yes, then how?

like image 280
Shaun Roselt Avatar asked Mar 29 '17 10:03

Shaun Roselt


2 Answers

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. |
like image 94
David Heffernan Avatar answered Sep 23 '22 15:09

David Heffernan


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.
like image 29
MartynA Avatar answered Sep 24 '22 15:09

MartynA