Jan 062013
 January 6, 2013  Posted by at 11:50 am Not So Stupid Questions  Add comments

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

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 🙂

  2 Responses to “Stupid Question 121: What is meant by ‘unsafe code’ in .Net?”

  1. Well it’s still possible to even get out of the CRL even with Safe Code, easiest is to run non thread safe .NET code threaded. Sure not a smart choise of things to do but just to point out that the CRL cannot really verify everything in ‘safe’ code.

    There is probobly more wierd cases that I don’t know of how you can break CRL still even with safe code.

    Also wierdly enought Microsoft have ways for you to ‘deal’ with this broken states.

    Example attributes such as http://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.handleprocesscorruptedstateexceptionsattribute.aspx make you able to be able to catch these exceptions. Thought if you do, it’s recomended that you shut the app down but at least you can do it more cleanly.

  2. 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.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



What is 15 + 7 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)