Iris Classon
Iris Classon - In Love with Code

Stupid Question 121: What is meant by ‘unsafe code’ in Net?

[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?

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

Leave a comment below, or by email.
Daniel Widegren
1/7/2013 11:49:01 PM
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. 
James Curran
1/8/2013 4:20:41 PM
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

comments powered by Disqus