Problem solve Get help with specific problems with your technologies, process and projects.

Writing unsafe code in C#

C# statements execute insafe or unsafe context. Safe context is the default, but code using pointers requires unsafe context.

Let other users know how useful this tip is by rating it below. Got a tip or code of your own you'd like to share? Submit it here!

C# statements execute in either a safe or an unsafe context. Safe context is the default, but any code using pointers requires unsafe context.The unsafe keyword denotes an unsafe context. Again, unsafe context is required for any operation involving pointers.

Unsafe code, or a block of code which is marked as unsafe, is managed by CLR, but a programmer is allowed to use pointers to manipulate memory directly. This code runs outside the control of memory management (GC). When you compile this code, it is unable to escape the watchful eye of the CLR. Unsafe can be applied as a modifier in the declaration of callable members such as methods, properties, constructors and extenders (but not static constructors).

Using unsafe code is more efficient than using references to access objects, imparts an extra layer and GC adds its overheads. You may use unsafe code to parts of your application where you want to be as efficient as possible. You may want to use COM interface method, which requires a pointer as an argument. You may also want to some C or C++ code that uses pointer if you don't want to convert the pointers to references.

Pointer is a variable that holds an address of a variable. Pointer variables have to be typed so that int* declares a 'pointer to int' and can only be used to hold the address of an int. Pointer variables can only be declared and used within unsafe blocks, because the GC has to be informed about using the pointer variables in your code.

using System;
class UnsafeTest
public static void Main()
{ int i = 5,k= 10;
int j = Add(&i,&k); // &i means address of i variable  
unsafe static int Add(int* p,int* q) //declare pointer variable int* p
return (*p + *q); // *p gets the value stored at location p 

Save the above code as UnsafeTest.cs.

Compile    c:\>csc UnasfeTest.cs 
run          c:\>UnsafeTest 

This was last published in March 2003

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.