Search code examples
c#c++-cliliterals

C++ literal char* or string variable error "cannot be a literal data member"


I'm working on a C# project which is dependent on a C++/CLI project. I'm using a few literal members (which are constants in C#) using types such as int or unsigned short that my C# project can access as a constant. I wanted to do the same with strings. Since it's possible in C#, I attempted to do it in C++...which I then ran into the problem.

using namespace System;

namespace TestNamespace
{
    static ref class TestClass
    {
        literal char* TestString = "fish";
    };
}

IntelliSense doesn't give me errors, but when this code is built, this error shows up: "'TestNamespace::TestClass::TestString': cannot be a literal data member"

I've changed char* to const char*, std::string, and pointers to other types of chars. I've done much digging on the internet about this stuff and understand some of it, but I have no idea why this isn't working. I've also read about string literals and thought that would help me. Nice stuff to know, but not necessarily in this situation.


Solution

  • Strings in .NET are the System::String^ data type, so you need to declare it as that type, not char*.

    using namespace System;
    
    namespace TestNamespace
    {
        static ref class TestClass
        {
            literal String^ TestString = "fish";
        };
    }
    

    Now TestString will be visible from C# as TestNamespace.TestClass.TestString.