Search code examples
c#c++-cli

Does the ^ symbol replace C#'s "ref" in parameter passing in C++/CLI code?


In C#, passing by reference is:

void MyFunction(ref Dog dog)

But in C++/CLI code examples I have seen so far, there is no use of ref but instead ^ symbol is used:

void MyFunction(Dog ^ dog)

Is the use of ^ symbol a direct replacement for ref when parameter passing? or does it have some other meaning I'm not aware of?

Additional Question: I also see a lot of:

Dog ^ myDog = gcnew Dog();

It looks like it's used like * (pointer) in C++.. Does it work similarly?

Thanks!


Solution

  • If Dog is a reference type (class in C#) then the C++/CLI equivalent is:

    void MyFunction(Dog^% dog)
    

    If Dog is a value type (struct in C#) then the C++/CLI equivalent is:

    void MyFunction(Dog% dog)
    

    As a type decorator, ^ roughly correlates to * in C++, and % roughly correlates to & in C++.

    As a unary operator, you typically still need to use * in C++/CLI where you use * in C++, but you typically need to use % in C++/CLI where you use & in C++.