How can I work with pointers?
-
16Don't.SLaks– SLaks2010-05-26 14:40:37 +00:00Commented May 26, 2010 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– Tim Lloyd2010-05-26 14:47:30 +00:00Commented May 26, 2010 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– Tim Lloyd2010-05-26 14:51:07 +00:00Commented May 26, 2010 at 14:51
-
This is somewhat unfocused, is there a specific purpose you have in mind?Ron Warholic– Ron Warholic2010-05-26 15:25:07 +00:00Commented May 26, 2010 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. msdn.microsoft.com/en-us/vcsharp/aa336809.aspxAnthony Pegram– Anthony Pegram2010-05-26 15:27:26 +00:00Commented May 26, 2010 at 15:27
4 Answers
Enough has been said about using the pointers in C#; nevertheless must if you use, here is an example of how you can do that.
Comments
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.
2 Comments
The best practice is to avoid unsafe code. So don't use pointers in C#.