String ^ MyString = gcnew String("abcd");

1.7k views Asked by At

I was reading the c++'s foreach syntax on MSDN:

// for_each_string1.cpp  
// compile with: /ZW  
#include <stdio.h>  
using namespace Platform;  

ref struct MyClass {  
   property String^ MyStringProperty;  
};  

int main() {  
   String^ MyString = ref new String("abcd");  

   for each ( char c in MyString )  
      wprintf("%c", c);  

   wprintf("/n");  

   MyClass^ x = ref new MyClass();  
   x->MyStringProperty = "Testing";  

   for each( char c in x->MyStringProperty )  
      wprintf("%c", c);  
}

I tried to find what the "^" means on google but I couldn't find anything (or my query wasn't correct)

What does it mean? Is it as a "*"? Is it as a "&"?

This syntax also applies to C#. Do they mean the same thing in both languages?

Piece of C# code:

using namespace System;

int main(){
  array<int>^ arr = gcnew array<int>{0,1,2,5,7,8,11};
  int even=0, odd=0;

  for each (int i in arr) {
    if (i%2 == 0)  
      even++;      
    else 
      odd++;         
  }

  Console::WriteLine(“Found {0} Odd Numbers, and {1} Even Numbers.”,
    odd, even);
}
2

There are 2 answers

4
user1610015 On

The "^" denotes a managed reference, which is used for managed types. It's like a pointer, but for managed types. The syntax doesn't exist in C#. In C#, the equivalent is just a variable of a reference type (as opposed to a value type), or a boxed value type.

As others have said, this is C++/CLI syntax which means you have to compile with the /clr option. C++/CLI is basically C++ with features of C# (or more generally, .NET).

0
Rafael Zhou On

https://learn.microsoft.com/en-us/cpp/extensions/handle-to-object-operator-hat-cpp-component-extensions?view=vs-2019 hope this link can help you. btw,^ is a special character and ignored by google search engine so you can not search that.