0

I've searched through the other answers similar to this topic, but haven't found anything completely relevant. I'm trying to assign values to some enumerations in C#, using values that are marked as static const in a C++/CLI file, which are compiled into a DLL and referenced in the C# project. All of that works fine, except that it gives me the "The expression being assigned to 'XXX' must be constant", which I would expect, if the C++/CLI value wasn't a constant. My C++/CLI code is auto-generated from 3rd-party vendor provided files, so my options for changing that side are extremely limited.

Here's some excerpts:

The C++/CLI file:

public ref class SEVERE_LEVEL sealed {
  public: 
    static const System::Int32 VALUE = 200;
  private:
    SEVERE_LEVEL() {}
};

And the C# file:

public enum LoggerLevel {
  SevereLevel = SEVERE_LEVEL.VALUE  // This gives the "must be constant" error
}

There are several different log levels, each defined in their own separate class in the C++/CLI file. I want to use the C# enum as a parameter type in some method calls to ensure only valid values are passed in. Any ideas how to make this work or suggestions on alternative designs?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Hamo2k1
  • 3
  • 3
  • That's a pretty quirky code generator. I'd just try to jam in a `public enum class` declaration, like it should have been. – Hans Passant Mar 11 '16 at 22:42

1 Answers1

0

The C++ const keyword doesn't map into anything in .NET.

C++/CLI adds new context-sensitive keywords to match the .NET functionality: initonly and literal.

If you use literal System::Int32 VALUE = 200; then it should work. There's no magic to make the C# compiler define enums using values that aren't marked "literal" in the .NET metadata.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Thank you for the suggestion! I wrapped the auto-generated classes in a new C++ class containing members marked with the "literal" keyword set equal to the previous static const members. This allows me to assign them to enums in C# perfectly fine. Thanks! – Hamo2k1 Mar 11 '16 at 23:42