Can you enumerate an enum?

In this code:

namespace ConsoleApplication6;

interface

   uses 
      System.Collections.Generic;


   type
      myenum = public enum( test1 , test2 ) of integer;


   type
      ConsoleApp = class
         public
            class method Main(args: array of string);
            class x : List<string>;
         end;

implementation

   class method ConsoleApp.Main(args: array of string);
      begin
      // add your own code here
      Console.WriteLine('Hello World.');

      x := new List<String>;
      x.add('test' );
      for each y in x do begin
         Console.WriteLine( y );
         end;

      for each e : integer in myenum do begin
         Console.WriteLine( e.ToString );
         end;
      end;
   end.

I can enumerate the list, but the compiler doesn’t seem to like me enumerating the enum. Is there a syntax that allows that?

Mark,
have you tried Enum.GetNames

Patrick,

Nope, didn’t try anything. I was just trying to find out if Oxygene had the syntax to enumerate an enum. I was reading an article where someone was proposing some code that allowed them to iterate the enum in C# and I was wondering if Oxygene allowed it.

And maybe if Oxygene doesn’t, that might be something to implement.

Hello Mark,

I have logged a feature request (68375: Enumerate an enum feature) for further review.

Best regards.

Is this feature ever implemented? It is very useful.

Thank you

Looks like this was done, yeah. I have an open Docs issue to document it, I’ll try to get to that next week…

Any update? How to enumerate an enum?

I was told it should just work. Can you give me a test case to show exactly what you are trying that doesn’t?

It should just work like what? What is the required syntax?

By trial and error, it seems the folowing works, but is it the correct way?

DeviceType = public enum (CPU, GPU, TPU);
for each el in typeOf(DeviceType).Constants do writeLn(el.Name + ‘:’ + el.Value.ToString);

for i: DeviceType := low(DeviceType) to high(DeviceType) do should do too. (iirc)

I thought we made it so you can just do

for d in DeviceType do

?

That doesn’t seem to work for me on Island/Windows.

Anyway, my goal is to have a generic method to convert a String to enum, and I found the following just works fine, using typeOf(T).Constants:

method AsEnum<T>(const aStr: NotNull<String>): Tuple of (Boolean, nullable T);   
begin
  result := (false, nil);
  if not typeOf(T).IsEnum then exit; 
  for each el in typeOf(T).Constants do begin
    if el.Name.Equals(aStr) then exit (true, T(el.Value));
  end;
end;
1 Like