Should you use pointers in your C# code? What are the benefits? Is it recommend by The Man (Microsoft)?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- Do the Java Integer and Double objects have unnece
If you have to.
Say that you need to false color a large grayscale image, say 2000x2000 pixels. First write the 'safe' version using
GetPixel()
andSetPixel()
. If that works, great, move on. if that proves to be too slow, you may need to get at the actual bits that make up the image (forget about Color matrices for the sake of the example). There is nothing 'bad' about using unsafe code, but it adds complexity to the project and should thus be used only when necessary.You should use them if you need them; mostly this will be when dealing with some tricky interop scenarios (for example when I wrote a managed wrapper for DPAPI in .NET 1.0 they were needed) but very occasionally it might be to improve performance (after profiling!) by using
stackalloc
or similar.It is recommended by Microsoft in as much as they are the designers of C#, and they made the decision to add the capability to write
unsafe
code in it. You can see from the choice of keyword and the requirement to delineate the methods/classes in which you write it using the keyword, that it isn't designed to be the de-facto implementation choice.course it isn't "recommended", that's why it's labeled "unsafe". But don't let that scare you away. Although, it should make you look twice at your code. Perhaps there is a managed way to do it?
Do it if it makes your code shorter and clearer.
"Follow your inclinations with due regard to the policeman round the corner." WSM
Reinterpretive like casts not supplied by BitConverter.
Specifically converting a unint into an int for hash functions where all you care about is the bits.
Using some useful, well reasoned about c or C++ idiomatic functions on structs where you need to treat them as a byte* of a well known length, again most useful for hashing.
Extremely fast binary serialization of (very specific) in memory structs (by doing it to an array of them) though to be honest this is better done by just dropping to C++/CLI.
It must be said that in many cases the task requiring pointers can often be solved better by doing it in C++/CLI and then importing this into you c# project as a dll. It doesn't change whether the code is 'safe' or not but it makes a bunch of useful functions for operating on pointer based structures more accessible. It also allows you to mess about with generic types or enums if you really want to.
The likelihood of most developers needing to do this is indeed remote. Useful when you need it though...