Search code examples
c#enumsc++-cliconstantsmixed-mode

Assign value to C# enum from C++/CLI const


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?


Solution

  • 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.