Should you use pointers in your C# code? What are the benefits? Is it recommend by The Man (Microsoft)?
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.
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.
Do it if it makes your code shorter and clearer.
"Follow your inclinations with due regard to the policeman round the corner." WSM
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 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...