Stupid Question 121: What is meant by ‘unsafe code’ in Net?
What is meant by ‘unsafe code’ in .Net?
I talked about unsafe code a few questions ago, but didn’t quite explain that. I was curious myself, what do we mean by unsafe code? Is it dangerous code? Bad-ass?
Well, unsafe code is “code whose safety cannot be verified by the CLR”. So if you choose to do so, you are on your own- it will be your responsibility.
How do you get unsafe?
First of all you must tell that you are about to do that, so you mark the application as unsafe. You do this by ticking the Allow unsafe code option on the projects properties, and preferably also mark the context that is unsafe ( be that a method, a type, or a code block) when working with pointers.
Why would you want to go unsafe?
Might increase app performance – if you know what you are doing.
Native function calls that require pointers
An example of unsafe code in C# can be found here, and if you want to read about the keyword unsafe go here. But wait, why not actually take an unsafe code tutorial? Yes, there is such a thing he he- not really sure I would call that a tutorial, its actually just three examples :)
Comments
The key thing to know about unsafe code, is that with a pointer to raw memory, bad things can happen if you're not careful (or if you are being deliberately malicious). Basically, any virus which takes control of your PC is doing things which can only be done in unsafe code.
Last modified on 2013-01-06