This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Visual Studio
VS 2003+

Compiling Unsafe Code in Visual Studio

Classes, structures and their members can be marked as unsafe when developing using C#. Unsafe code is required for some interoperability scenarios and can improve performance. As the compiled code can be unstable, normal compilation is not supported.

Unsafe Code

An uncommon task when developing software using C# is creating unsafe code. This type of code allows the creation of pointers, similar to those that you might use in C++. These can be used to improve the performance of some operations by removing the boundary checks that C# would normally include. Pointers are also required if you need to use some API calls using Platform Invocation Services (P/Invoke).

The problem with unsafe code is that the checks that C# adds make programs developed using the language much safer. With normal C# code, buffer underruns and overflows are essentially eliminated. With unsafe code they can easily be reintroduced, leading to potential vulnerabilities, security problems or instability in the final assembly. In recognition of this, the compiler will not build unsafe code unless explicitly told to do so. If you create an unsafe code block and follow the normal build process you will see the following complier error:

Unsafe code may only appear if compiling with /unsafe

As the error indicates, if you are using the command-line compiler you can add the /unsafe switch to enable the code to be built. If you are using Visual Studio, you can also enable unsafe code within the project's properties.

If you are using Visual Studio 2003, open the project's property pages, expand the Configuration Properties option and select the Build section. You can enable the compilation of unsafe code blocks by ticking the "Allow Unsafe Code Blocks" checkbox.

For Visual Studio 2005 or later, open the project's properties and choose the Build tab. You can enable or disable unsafe code compilation with the "Allow Unsafe Code" checkbox. The image below shows Visual Studio 2005's Build properties with unsafe code enabled:

Visual Studio Allowing Unsafe Code

27 September 2011