Introduction to unsafe code

suggest change

C# allows pointer variables in a function or a code block marked with the unsafe modifier. Unsafe code uses pointers. It is still C#, not native unmanaged code.

A pointer is a variable whose value is the address of another variable, the direct address of the memory location. Similar to any variable or constant, you must declare a pointer before you can use it to store an address.

The general form of a pointer declaration is:

type *var-name;

Following are valid pointer declarations:

int    *ip;    /* pointer to an integer */
double *dp;    /* pointer to a double */
float  *fp;    /* pointer to a float */
char   *ch;    /* pointer to a character */

The following example illustrates the use of pointers in C#, using the unsafe modifier:

using System;
namespace UnsafeCodeApplication
{
   class Program
   {
      static unsafe void Main(string[] args)
      {
         int var = 20;
         int* p = &var;
         Console.WriteLine("Data is: {0} ",  var);
         Console.WriteLine("Address is: {0}",  (IntPtr)p);
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it prints the value and that run's address. The address is not a fixed number:

Data is: 20
Address is: 0x...

Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe:

// safe code
unsafe
{
    // you can use pointers here
}
// safe code

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents