Enumerations in Delphi with custom values
Asked Answered
O

4

6

It is possible to declare enums with custom values in Delphi 5 like this?:

type
  MyEnum = (meVal1 = 1, meVal2 = 3); // compiler error

Thanks!

Oversleep answered 6/9, 2010 at 7:43 Comment(0)
O
5

In older Delphis you can do

type
  MyEnum = (meUnused1, meVal1, meUnused2, meVal2);
Opulent answered 6/9, 2010 at 11:53 Comment(0)
R
3

This is legal according to this article. I do recall that in early versions of Delphi supplying values wasn't supported.

It might help to provide the 'compiler error' you received. Also, what version of Delphi are you using?

Roussillon answered 6/9, 2010 at 7:54 Comment(1)
This should indeed be legal, see also: docwiki.embarcadero.com/RADStudio/2010/en/…Limbate
E
3

If you have an older version of Delphi (<= D5 IIRC) you can't do this. Maybe you can replace the enum by constants? Something like

const
  meVal1 = 1;
  meVal2 = 3;

type
  TMyEnum = Byte; // or Integer or ... - depends on your needs.

Unfortunately, the compiler can't do as much error checking for you with this as with an enum type.

Ebonyeboracum answered 6/9, 2010 at 8:16 Comment(0)
B
2

As a somewhat ugly extension to the answer by Ulrich you could do something like the following:

type
  TMyEnum = (meVal1, meVal2);

const
  MY_ENUM_VALS: array[TMyENum] of integer = (1, 3);

and access them as

if (aVal = MY_ENUM_VALS[meVal2]) then...

Not pretty, I grant you, but at least that way you get a little more compiler error checking for those earlier versions of Delphi.

Boatbill answered 6/9, 2010 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.