Tuesday, February 20, 2007

const (in C++/CLI) considered harmful

Today I found the following "gotcha" in combining C++/CLI and C#.
Create a C++/CLI dll containing something along the lines of:

public ref class Foo
{
public:
static const int BAR = 42;
};
Use that from C#, maybe like so:
int temp = Foo.BAR;
Foo.BAR
= -1;
MessageBox.Show(
string.Format("The answer is: {0} ...or {1}",
temp, Foo.BAR),
"WTF!?!");
Wait, that should not be possible! We just said that BAR was const in the C++/CLI code didn't we?

The problem is that it is possible (and gives the following screenshot):

Digging deeper reveals that C++/CLI const turns into an ordinary field with an optional modifier IsConst that languages are free to ignore, (which e.g. C# does).

If you in fact want a "constant" constant (which is probably why you wrote const in the first place?), then you will need to use literal in C++/CLI to get the same result as a C# const.

No comments: