2

How can I work with pointers?

6
  • 16
    Don'​​​​​​t. Commented May 26, 2010 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. Commented 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? Commented May 26, 2010 at 14:51
  • This is somewhat unfocused, is there a specific purpose you have in mind? Commented 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.aspx Commented May 26, 2010 at 15:27

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

The wrapper class is a good idea. You really want to keep your unsafe code in one place.
Implement the Dispose and destructor pattern for when dispose is not called.
0

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

1 Comment

A better suggestion would be to point out where they might be useful rather than offering up such a blanket statement.
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. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.