Reader Level:

Unsafe Code in C#

By Vineet Kumar Saini on Dec 06, 2011
In this article you will see the use of the 'unsafe' keyword in C#.

As you know, a Pointer is a variable which holds the address of another variable. If we want to use a pointer in C# then we use the  "unsafe" keyword for that purpose. Unsafe code is code which does not executed under the full management of common language runtime (CLR). It can cause some problems therefore each use must be marked as "unsafe". Unsafe code is also known as unmanaged code because it is not execute under the full management of CLR. There are two types of code in C#, Which are as follows:

  • Manages code
  • Unmanaged code

Managed Code : The code which is executed under the full management of CLR, is called managed code. Managed Code include programmers convenience and enhanced security .

Unmanaged code : The code which does not executed under the full management of common language runtime (CLR), is called unmanaged code. We can say unmanaged code is directly executed by the computer's CPU.

To set the compiler option in the Visual Studio development environment




When we run the the program then there will be an error corresponding to unsafe code. For remove this error we go to application properties.


Now we will go to build option and check the Allow unsafe code.


Run application (Press F5).


To set compiler option programmatically

First of all we write the program on notepad then save in any drive with name "unsafe.cs".

When we compile this program then we write "csc/unsafe unsafe.cs".



So unsafe code is unmanaged code i.e. which does not execute under full management of CLR. We can say that, when we want use of pointer in C# then we will use unsafe keyword.

Vineet Kumar Saini

Vineet Kumar Saini is MCA qualified with Honors from SunderDeep Engineering College Ghaziabad. Currently he is working as a "WEB Developer" at AzylApps Technology Pvt. Ltd.