9

Is there a way to put nested enumerations in Delphi into an own naming space?

This code produces an E2004: Identifier redeclared, as both enumerations contain "unknown".

TMyType1 = class
public type
  TMyType1Enum = (unknown, val1, val2);
public
  constructor Create();
  ...
end;

TMyType2 = class
public type
  TMyType2Enum = (unknown, other1, other2, other3); // causes E2004
public
  constructor Create();
  ...
end;

In C++ the identifiers of the enum elements were both in differnet scopes (TMyType1::unknown and TMyType2::unknown).

Is there a possibility to achieve something like this in Delphi except pre- or suffixing the identifiers (MyType1EnumUnknown, MyType1EnumVal1, ..., MyType2Enumunknown,...)?

Chris
  • 1,508
  • 1
  • 11
  • 30
  • 2
    The answer below is perfect but from a coding standards point of view, prefixes are normally used in Delphi for enums. Take a look at `TFontStyle`, as an example. It's definition looks like this: `TFontStyle = (fsBold, fsItalic, fsUnderline, fsStrikeOut)` – Graymatter Jul 29 '16 at 18:40

1 Answers1

13

Try $SCOPEDENUMS. From http://docwiki.embarcadero.com/RADStudio/en/Scoped_Enums_(Delphi):

type
  TFoo = (A, B, Foo);
  {$SCOPEDENUMS ON}
  TBar = (A, B, Bar);
  {$SCOPEDENUMS OFF}

begin
  WriteLn(Integer(Foo)); 
  WriteLn(Integer(A)); // TFoo.A
  WriteLn(Integer(TBar.B));
  WriteLn(Integer(TBar.Bar));
  WriteLn(Integer(Bar)); // Error
end;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Uli Gerhardt
  • 13,748
  • 1
  • 45
  • 83
  • FWIW, the docwiki seems to be offline, right now. But the same documentation can be found in the installed help files that come with Delphi/RAD Studio. We just can't link to it, from here. – Rudy Velthuis Nov 19 '17 at 10:27