SomeOne
SomeOne

Reputation: 365

Enumerations in Delphi with custom values

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

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

Thanks!

Upvotes: 6

Views: 2598

Answers (4)

gabr
gabr

Reputation: 26850

In older Delphis you can do

type
  MyEnum = (meUnused1, meVal1, meUnused2, meVal2);

Upvotes: 5

shunty
shunty

Reputation: 3768

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.

Upvotes: 2

Uli Gerhardt
Uli Gerhardt

Reputation: 14001

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.

Upvotes: 3

Ben Laan
Ben Laan

Reputation: 2617

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?

Upvotes: 3

Related Questions