Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of C# 'ref' keyword compared to C++

Tags:

c++

c#

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?

like image 398
ElmsPlusPlus Avatar asked Aug 13 '12 13:08

ElmsPlusPlus


People also ask

Is C used today?

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.

Why C is used in computer?

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.


1 Answers

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).

like image 53
Konrad Rudolph Avatar answered Oct 01 '22 00:10

Konrad Rudolph