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?
C exists everywhere in the modern world. A lot of applications, including Microsoft Windows, run on C. Even Python, one of the most popular languages, was built on C. Modern applications add new features implemented using high-level languages, but a lot of their existing functionalities use C.
C programming language uses blocks to separate pieces of code performing different tasks. This helps make programming easier and keeps the code clean. Thus, the code is easy to understand even for those who are starting out. C is used in embedded programming, which is used to control micro-controllers.
Is this a correct analogy?
Despite what the other answers say, no. What ref
means 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:
public void CPlusPlus(type*& bar)
The whole point about ref
is that you can change the reference being passed in. And you can’t do that in C++ by simply passing a pointer:
void f(type* bar) {
bar = new_address;
}
type* x;
f(x);
This code won’t change the caller’s value of x
. If you had passed bar
as type*&
, on the other hand, it would have changed the value. That is what ref
does.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With