Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a C# Reference and a Pointer?

I do not quite understand the difference between a C# reference and a pointer. They both point to a place in memory don't they? The only difference I can figure out is that pointers are not as clever, cannot point to anything on the heap, are exempt from garbage collection, and can only reference structs or base types.

One of the reasons I ask is that there is a perception that people need to understand pointers well (from C, I guess) to be a good programmer. A lot of people who learn higher level languages miss this out and therefore have this weakness.

I just don't get what is so complex about a pointer? It is basically just a reference to a place in memory is it not? It can return its location and interact with the object in that location directly?

Have I missed a massive point?

like image 576
Richard Avatar asked Jan 09 '09 23:01

Richard


People also ask

Which type of AC is best for home?

As compared to a normal air conditioner, an inverter AC offers better, more consistent cooling. This type is also more energy efficient and quieter too.

Does Max AC make it colder?

Max A/C recirculates the air inside your car and is best used when the inside air is cooler than the air outside. Use standard air conditioning until the air in your car cools off a bit and then hit Max A/C to cool it down even more.

What is difference between AC and HVAC?

An HVAC unit heats, cools, and ventilates your home; and an AC unit only cools your home.


1 Answers

There is a slight, yet extremely important, distinction between a pointer and a reference. A pointer points to a place in memory while a reference points to an object in memory. Pointers are not "type safe" in the sense that you cannot guarantee the correctness of the memory they point at.

Take for example the following code

int* p1 = GetAPointer(); 

This is type safe in the sense that GetAPointer must return a type compatible with int*. Yet there is still no guarantee that *p1 will actually point to an int. It could be a char, double or just a pointer into random memory.

A reference however points to a specific object. Objects can be moved around in memory but the reference cannot be invalidated (unless you use unsafe code). References are much safer in this respect than pointers.

string str = GetAString(); 

In this case str has one of two state 1) it points to no object and hence is null or 2) it points to a valid string. That's it. The CLR guarantees this to be the case. It cannot and will not for a pointer.

like image 175
JaredPar Avatar answered Sep 28 '22 02:09

JaredPar