C++/CLI : Why can't I pass Strings by reference?

Casebash picture Casebash · Oct 14, 2010 · Viewed 9.9k times · Source

Why doesn't Microsoft's C++/CLI allow me to pass strings by reference? I received the following error:

C3699: '&': cannot use this indirection on type 'System::String'

Answer

Ðаn picture Ðаn · Oct 14, 2010

First of all, there are really two Microsoft-specific C++ dialects for .NET: the older "Managed C++" (Visual Studio 2002 and 2003) and C++/CLI (Visual Studio 2005 and later).

In C++/CLI, System::String^ is a .NET reference to a string; some authors call this a "tracking pointer" to compare and contrast it with a normal C++ pointer. As in C++, you can pass .NET references "by reference", but instead of using &, you use %, as in:

void makeStr(System::String^ %result) {
   result = gcnew System::String("abc");
}