Search code examples
enumsc++-cli

Enum::GetValues() returns zero elements


I've got problem with method Enum::GetValues(). It returns nothing - no error, no elements. Length of 'a' is zero. This code is from Microsoft website, so this is official example. I can't make it work. Project is for .NET framework 4.7.2, this should be ok. I'm using VS2022 with all updates. Does anybody has any suggestion? Thanks

Link: https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-6.0

using namespace System;
enum class Colors
{
   Red, Green, Blue, Yellow
};
    
int main()
{
   Console::WriteLine(  "The values of the Colors Enum are:" );
   Array^ a = Enum::GetValues( Colors::typeid );
   for ( Int32 i = 0; i < a->Length; i++ )
   {
      Object^ o = a->GetValue( i );
      Console::WriteLine(  "{0}", Enum::Format( Colors::typeid, o,  "D" ) );
   }
}

The example should produce:

//       The values of the Colors Enum are:
//       0
//       1
//       2
//       3

But the result is only:

The values of the Colors Enum are:

Solution

  • enum class is a c++11 scoped enum, not a .net enum, see the note at https://learn.microsoft.com/en-us/cpp/dotnet/how-to-define-and-consume-enums-in-cpp-cli

    To make it a .net enum you need to add private or public. E.g.:

    private enum class Colors
    {
       Red, Green, Blue, Yellow
    };