2

How can I work with pointers?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
user351011
  • 29
  • 2
  • 16
    **Don'​​​​​​t**. – SLaks May 26 '10 at 14:40
  • 4
    Explain 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 Answers4

2

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.

KMån
  • 9,896
  • 2
  • 31
  • 41
1

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.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
0

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. :)

Sebastian 506563
  • 6,980
  • 3
  • 31
  • 56
0

The best practice is to avoid unsafe code. So don't use pointers in C#.

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
  • 10
    A 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