How to work with unsafe code in .Net

How to work with unsafe code in .Net


Take advantage of the unsafe keyword to write unmanaged code in .Net


The C# programming language doesn't allow you to work with pointers by default. You need to use the unsafe keyword to define an unsafe context and write code that uses pointers. Unsafe code helps you write unmanaged code that wouldn't be handled by the execution environment of the CLR. This article takes a look at how we can work with unsafe code in the managed environment of .Net.

What is unsafe code anyway?

With unsafe code, the safety of the code cannot be verified by the CLR. In other words, unsafe or unmanaged code is executed outside of the context of the CLR. Unsafe code helps you invoke native functions using pointers. Note that when writing unsafe code you should ensure the program doesn't incur any security risks, memory faults, or so on. To write unsafe code, you should use the unsafe keyword. You define methods, types, and code blocks as unsafe using the unsafe keyword.


A pointer is a variable that points to the address of another variable. In other words, a pointer holds the memory address of another variable or a memory location. Note that the data type of a pointer should match the data type of the variable to which it points. Hence, for a pointer to indicate an integer variable, the type of the pointer should be integer. The three operators that you would frequently make use of while working with pointers include the following:

  • *
  • &
  • ->

The following piece of code shows how you can define a pointer and make it point to the address of a variable.

int i = 100;

int *ptr = & i;

Refer to the code snippet above. In the first statement we assign the value 100 to an integer variable. In the next statement we define an integer pointer and make it point to the address of the variable using the & operator.

Here's a snippet of code that illustrates how we can use the unsafe keyword to display the memory address of a variable.

static void Main(string[] args)




            int i = 100;

            int* ptr = &i;


           ("The value of i is : " + i);


          ("The memory address of i is : " + (int)ptr);




Note that usage of the unsafe keyword. If you omit unsafe and compile the above code, you would see the following error.

"Pointers may only be used in an unsafe context".

The above error message clearly states that you should write your unsafe code within an unsafe context -- exactly what unsafe provides you.

Assuming you're using Visual Studio IDE for writing and compiling your program(s) that leverage unsafe code, you should enable unsafe code for your project in the Visual Studio IDE. To do so, follow these steps:

  • Select the project and right-click on it
  • In the project properties window, click on the Build tab
  • Next, select the "Allow unsafe code" check box

Note that you can also compile your program that contains unsafe code using the csc command-line compiler as shown below:

csc /unsafe myprogram.cs

The above program when executed would display the value and also the memory address of the variable i.

You can also mark a method as unsafe via the unsafe keyword. Here's an example that shows how you can do this:

public unsafe void Compute(int* ptr)


      *ptr = (*ptr) * 10;


You can now invoke the Compute function as shown below.

unsafe {

            int i = 100;

            int* ptr = &i;


            Console.WriteLine("The value of the variable i is : " + i);


When you execute the above code snippet, you would observe that the value of the variable i has been changed from 100 (its initial value) to 1,000. The Compute function accepts a pointer as an argument and multiplies the value of the variable to which the pointer points by 10. Note that *ptr refers to the content of the variable to which ptr points, which incidentally is 100. This value is multiplied by 10 -- hence the result.

When working with unsafe code in a managed environment you might need to use the fixed keyword to logically place the variable in memory so that the runtime doesn't move the variable around in memory while compacting the memory due to heap fragmentation. In essence, you can use the fixed keyword to eliminate the issues related to invalid pointers. You can also use fixed to pin an array and retrieve pointer to the data in the array.

I would discuss more on unmanaged code in my future articles here.

This article is published as part of the IDG Contributor Network. Want to Join?

From CIO: 8 Free Online Courses to Grow Your Tech Skills
View Comments
Join the discussion
Be the first to comment on this article. Our Commenting Policies