0

First of all: I am using C++-CLI, but I would like to know the solution for C# as well.

Using following code

assembly "basics"

public ref class CONSTS abstract sealed
{
public:
  static const int  SUCCESS     = 1;
  static const int  InProgress  = 101;
};

assembly "program"

enum class EnumReplyLLI
{
  Nothing = 0,
  SUCCESS = CONSTS::SUCCESS,      // C2057
  Busy    = CONSTS::InProgress,   // C2057
  ...
};

I get the error C2057: expected constant expression

How can I define a compile-time constant and use it in another assembly?
My code is almost identical to the accepted answer in this SO post, but this does not work.

Community
  • 1
  • 1
Tobias Knauss
  • 3,361
  • 1
  • 21
  • 45

2 Answers2

2

The real equivalent of C# const in C++/CLI is literal, so your CONSTS class should look like:

public ref class CONSTS abstract sealed
{
public:
    literal int  SUCCESS = 1;
    literal int  InProgress = 101;
};
Matteo Umili
  • 3,412
  • 1
  • 19
  • 31
  • doesn't compile. Error C4693. See http://bytes.com/topic/net/answers/603702-abstract-sealed-literal. As stated by @BenVoigt in this post, it would be a compiler bug... I am using VS 2008 SP1. – Tobias Knauss Oct 14 '15 at 13:49
  • @TobiasKnauss Just tried and it compiles with VS2013 without warnings, anyway C4693 is a warning, not an error. Also, the raising of the warning was a bug in previous versions of the compiler. If it doesn't compile can you try with http://www.coderforlife.com/c-cli-static-classes-with-delegates-and-literals/ ? – Matteo Umili Oct 14 '15 at 13:54
  • VS 2008 shows errors to me, so I can't compile unfortunately. Changing the compiler isn't an option here, so it seems like there is no solution to my issue. – Tobias Knauss Oct 14 '15 at 13:56
  • 1
    Can you take off `abstract sealed`? I know that would make the class non-static but if you don;t have any "real" instance members it shouldn't matter. – D Stanley Oct 14 '15 at 13:58
  • I removed `sealed`, that was sufficient. Not perfect, but working. I won't instantiate it anyway. Thanks a lot! – Tobias Knauss Oct 14 '15 at 14:02
1

Not sure why it's not working in C++, but here's the equivalent code in C#:

public static class CONSTS 
{
  public const int  SUCCESS     = 1;
  public const int  InProgress  = 101;
};

enum EnumReplyLLI
{
  Nothing = 0,
  SUCCESS = CONSTS.SUCCESS,     
  Busy    = CONSTS.InProgress,  
};
D Stanley
  • 149,601
  • 11
  • 178
  • 240