Search code examples
c++visual-c++clr

Unable to iterate over enum


I'm currently unable to iterate over my Enum values using the following code:

enum class Animals { Ducks, Giraffes, Hamster };

Array^ temp = Enum::GetValues(Animals::typeid);
Console::WriteLine("LENGTH = " + temp->Length);
for (int iter = 0; iter < temp->Length; iter++)
{
    Console::WriteLine("ITER = " + iter);
}

It results in the following:

LENGTH = 0

I have followed the following documentation entry:

https://msdn.microsoft.com/en-us/library/system.enum.getvalues(v=vs.110).aspx

Thanks for your time


Solution

  • The C++11 language revision has adopted several keywords that were in use in C++/CLI. Like nullptr, override, final. And the enum class keyword. That makes your Animals type an unmanaged type in recent VS versions and Enum::GetValues() incapable of discovering enum values since it relies on reflection.

    override and final don't byte since they are contextual keywords. nullptr is troublesome, but it stays the managed flavor and __nullptr is the unmanaged flavor. The workaround for enum class is unintuitive, you must declare it with a top-level type visibility specifier (public or private). Syntax that isn't valid in native C++. Fix:

       public enum class Animals { Ducks, Giraffes, Hamster };