Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new elements to an enumerated type

Given an enumerated type declaration in Delphi such as:

TMyType = (Item1, Item2, Item3);

is there any way to add a fourth item, say Item4, to the enumerate type at runtime so that at some point during the application's execution I have:

TMyType = (Item1, Item2, Item3, Item4);

Or are types fixed in Delphi?

like image 740
rhody Avatar asked Dec 01 '22 01:12

rhody


2 Answers

You can create a set.

The following example initializes the set with items item1 and item4. After that item5 is added. It shows whether item5 is in the set, before and after adding, so you'll get this output:

FALSE
TRUE

Example:

program Project1;
{$APPTYPE CONSOLE}
uses SysUtils;

type
  TMyType = (Item1, Item2, Item3, Item4, Item5,Item6);
const
  cItems1And4 : set of TMyType = [Item1,Item4];
var
  MyItems:set of TMyType;

begin
  MyItems := cItems1And4;
  WriteLn(Item5 in MyItems);
  Include(MyItems,Item5);
  WriteLn(Item5 in MyItems);
  ReadLn;
end.

...

I wanted to type the following as a comment to Andreases reply, but the comment system doesn't let me properly format stuff..

If you're not stuck with an ancient Delphi, this is probably a better idea:

  TComputerType = record
    const
      Desktop = 0;
      Server = 1;
      Netbook = 2;
      Tabled = 3;
  end;

That makes sure you don't pollute your namespace, and you'll get to use it as if it's a scoped enum:

 TComputerType.Netbook

I usually do it like that nowadays.. You can even create some handy helper-functions or properties in there, for example to convert from and to strings.

like image 196
Wouter van Nifterick Avatar answered Dec 04 '22 01:12

Wouter van Nifterick


No, you 'can't' do this. It is against the way Delphi works. (Recall that Delphi checks your types already at compile time.)

If I were you, I'd not do

TComputerType = (ctDesktop, ctServer, ctLaptop, ctNetbook, ctTablet)

Instead, I'd do

TComputerType = integer;

const
  COMPUTER_TYPE_DESKTOP = 0;
  COMPUTER_TYPE_SERVER = 1;
  COMPUTER_TYPE_LAPTOP = 2;
  COMPUTER_TYPE_NETBOOK = 3;
  COMPUTER_TYPE_TABLET = 4;

I am sure you get why.

like image 27
Andreas Rejbrand Avatar answered Dec 04 '22 02:12

Andreas Rejbrand