How can I work with pointers?
-
16**Don't**. – SLaks May 26 '10 at 14:40
-
4Explain why you want\need to use pointers. That should illicit some better answers and debate. Using pointers in C# can be seen as quite contentious if there is no context to why you want to use them. – Tim Lloyd May 26 '10 at 14:47
-
If this topic is not a duplicate and goes somewhere, perhaps a community wiki would be helpful for those who come from languages where pointer usage is common? – Tim Lloyd May 26 '10 at 14:51
-
This is somewhat unfocused, is there a specific purpose you have in mind? – Ron Warholic May 26 '10 at 15:25
-
I've heard it said that you start by reading the Unsafe Code chapter of the C# Language Specification *twice* before even considering it. http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx – Anthony Pegram May 26 '10 at 15:27
-
Possible duplicate: http://stackoverflow.com/questions/985691/pointers-in-c – Mateen Ulhaq Nov 24 '11 at 06:29
4 Answers
In addition to the other answer that already points out that pointers and unsafe code should be avoided if possible.
You want to avoid having unsafe
code spread out all over your code base so I'd suggest writing a .Net wrapper on top of all your unsafe calls and that way you only need to worry about it in one place. Possibly even create a class library for it, but that depends on what exactly you're doing.
It will obviously be very important that whoever uses the wrapper remembers to call the wrapper's Dispose
methods and similar to make sure that any pointers or other unmanaged resources are disposed of properly, but that's not different from the rest of your code.

- 54,199
- 15
- 94
- 116
-
The wrapper class is a good idea. You really want to keep your unsafe code in one place. – ChaosPandion May 26 '10 at 15:02
-
Implement the Dispose **and** destructor pattern for when dispose is not called. – Tim Lloyd May 26 '10 at 15:21
I know that this topic is old but i found myself after swiching from C++ to C# in simulate behawior of pointer in some case just by using set/get properties. :)

- 6,980
- 3
- 31
- 56
The best practice is to avoid unsafe code. So don't use pointers in C#.

- 66,094
- 13
- 157
- 251
-
10A better suggestion would be to point out where they might be useful rather than offering up such a blanket statement. – ChaosPandion May 26 '10 at 14:41