You might have noticed that I pointed out (pun intended) in the last question (what are pointers?) that we do. Besides references being pointers we have also something we refer to as *just* pointers, the true pointers in C#. Pointers point and references reference- and the GarbageCollector can manage the latter but not the first.
How I know? I try to make it to all Robert C. Martins sessions at conferences. And during each session he asks the crowd : “Do we have pointers in C#?”. Usually only a few say yes, now that you know- make sure to answer right. I of course made sure to learn a little bit about pointers after the sessions(s), as the importance of understanding them was a recurrent theme .
So let’s forget about references and talk about pointers instead. Since they point to a specific place in memory, they pose a problem to the GarbageCollector. The GC won’t know what resides at that address, which makes it pretty hard- well actually impossible- to manage the life of the object.
Pointers in C# are limited, and not really recommended to use- but they do seem to have some usage,- since I haven’t used them I don’t feel like the right person to talk about the usage scenarios, but there is an interesting discussion about the usage of pointers in C# here for the curious. To sum it up, some usage scenarios mentioned are: (from MSDN)
- Dealing with existing structures on disk
- Advanced COM or Platform Invoke scenarios that involve structures with pointers in them
- Performance-critical code
When you use pointers in C# you are required to use a keyword, unsafe. This keyword can be used in the type or member declaration. Pointers do not inherit from object, and lack therefore that conversation ability. For the same reason they can only be of basic types, such as: int, uint, long, ulong, char, float, double, decimal, bool etc. You get the point. 😉
Declaring pointers in C# :
int* p1, p2, p3;
int *p1, *p2, *p3;