Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pointer in C++ and reference type in C#

In C++ a pointer is a pointer to an address of memory where another variable is stored and in C# a reference is some how same. What is the difference between these two?

like image 264
Firoz Avatar asked Jan 27 '10 10:01

Firoz


2 Answers

In C# the reference type will be automatically garbage collected when no longer needed.

like image 149
Darin Dimitrov Avatar answered Sep 23 '22 02:09

Darin Dimitrov


For me, the concept is the same, or at least intended to be the same, but the actual use given, is not.

When we talk about pointers or reference we are talking about a concept. This variable "points to" or its a "reference" to something else, something that is stored somewhere else.

If I use that reference, for example by updating the value, I'm actually updating the referenced object, the object the variable points to. If I have an object referenced from two different places, I'm actually update the same thing from both places.

So the concept can be related to your address in the real world, is just a way to refer to other thing, and that reference can be shared, like many people having my address.

The difference is more on how it has been used and what's been allowed by the language. Note that the implementation details of the reference or pointer are not implicit in the concept itself. In C# that continues to be true.

A reference is a reference and being that so, it just does not make sense to sum two reference, or to add one to a reference ... what would that even mean? I can't add two home addresses (like Baker Street + Home Street) ...

In C++ the implementation detail of the reference is actually the reference. That way a pointer is not just a pointer, its also (and is used as) a memory address. That way, for example, you can add to pointers, because it actually makes sense to add two memory addresses to obtain another one, or to add 4 to a memory address. So in C++ a pointer stopped being a concept an became a name given to an actual implementation detail.

That is why, in C#, pointers and reference are different things. Because, through semantically the meaning is quite similar, they wanted to differentiate from the old concept of C and C++, where a pointer had became the same as a memory address.

I recommend you read the article "References are not addresses" from Eric Lippert where I believe he does a great job explaining the differences.

like image 37
Jorge Córdoba Avatar answered Sep 22 '22 02:09

Jorge Córdoba