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
Unsafe code is a fully supported function of the .NET CLR. The benefits are performance and compatibility with binary code. The runtime is a sandbox which prevents you from crashing and burning, but that comes with a cost. In situations where you are doing extremely intensive operations against large blobs in memory, for example image manipulation, it is faster to step outside the normal safety the runtime provides.
That having been said, I think most people here would say "don't do it". The vast majority of .NET developers will not run into a case in their normal activities that can only be solved by using unsafe code.
using Unsafe code is like forgetting the benenfits of the .Net Framework, i used them once to created old fashioned structures like stacks and stuff but that was only for school, nowadays i havent had the need to use them.
I would say the main issues are:-
I'm sure there's more that could be added to the list; in general, as others' have said - avoid unless you have to.e.g. calling an unmanaged method via p/invoke which requires some special pointer funking. Even then the marshaller will mostly prevent the need for it, mostly.
'The man' also say avoid unless necessary, basically.
Oh, nice article about pinning here on MSDN by the way.
I used unsafe code to use impersonation to allow services access to network shares. It is not a problem if you know what you're doing.
From "The Man" himself:
The use of pointers is rarely required in C#, but there are some situations that require them. As examples, using an unsafe context to allow pointers is warranted by the following cases:
The use of unsafe context in other situations is discouraged.
Specifically, an unsafe context should not be used to attempt to write C code in C#.
Caution:
Code written using an unsafe context cannot be verified to be safe, so it will be executed only when the code is fully trusted. In other words, unsafe code cannot be executed in an untrusted environment. For example, you cannot run unsafe code directly from the Internet.
Reference
I can't remember ever having to do so - but I haven't done much interop. That's the most common application, I believe: calling into native code. There are a very few times where using pointers allows you to optimise some code, but it's pretty rare in my experience.
If it's any guide, I consider myself to be pretty experienced in C# but if I had to do any unsafe code I'd have to consult the spec/books/MSDN to guide me. Of course there will be plenty of people who are happy with unsafe code but less familiar with (say) query expressions...