I have mainly worked in C++ and I am now using C# at my new job, and after doing some reading on here about the ‘ref’ keyword and c# value vs reference types I am still finding some confusion with them.
As far as I’m understanding these if you were passing these to a method these would be analogous C++ styles:
Value types:
public void CSharpFunc(value)
and
public void CPlusplusFunc(value)
Reference types:
public void CSharpFunc(reference)
and
public void CPlusPlusFunc(&reference)
‘ref’ / pointer
public void CSharpFunc(ref bar)
and
public void CPlusPlus(*bar)
Is this a correct analogy?
Despite what the other answers say, no. What
refmeans in terms of C++ actually depends on the type. For value types, your assessment is correct (or close enough). For reference types, a more suitable analogy would be a reference-to-pointer:The whole point about
refis that you can change the reference being passed in. And you can’t do that in C++ by simply passing a pointer:This code won’t change the caller’s value of
x. If you had passedbarastype*&, on the other hand, it would have changed the value. That is whatrefdoes.Furthermore, a reference in C# is quite unlike a reference in C++, and much more like a pointer in C++ (in that you can change which object the reference refers to).