Friday 21 February 2014

Unsafe code using C#

Introduction

In unsafe code or in other words unmanaged code it is possible to declare and use pointers. But the question is why do we write unmanaged code? If we want to write code that interfaces with the operating system, or want to access memory mapped device or want to implement a time critical algorithm then the use of pointer can give lots of advantages.
But there are some disadvantages of using pointers too. If pointers were chosen to be 32 bit quantities at compile time, the code would be restricted to 4gig of address space, even if it were run on a 64 bit machine. If pointers were chosen at compile time to be 64 bits, the code could not be run on a 32 bit machine.
In C# we can write unsafe code with the modifier unsafe. All the unsafe code must be clearly marked with theunsafe modifier. Writing unsafe code is much like writing C code in a C# program.

Sample


using System;

class MyClass 
{
public static void Main() 
       {
unsafe 
               {
int i = 10;
int* p = &i;
Console.WriteLine("Value is " + i);
Console.WriteLine("Address is " + (int)p);
}
}
}

Output

Value is 10
Address is 1244316

Setting

To set this compiler option in the Visual Studio development environment

  1. Open the project's Properties page.
  2. Click the Build property page.
  3. Select the Allow Unsafe Code check box.