C++ Tutorial on C# Unsafe Codes

c# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. the unsafe code or the unmanaged code is a code block that uses a pointer variable.

note − to execute the programs mentioned in this chapter at codingground, please set compilation option in project >> compile options >> compilation command to

mcs *.cs -out:main.exe -unsafe"

pointers

a pointer is a variable whose value is the address of another variable i.e., 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 any variable 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 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}",  (int)p);
         console.readkey();
      }
   }
}

when the above code wass compiled and executed, it produces the following result −

data is: 20
address is: 99215364

instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe. the example in the following section shows this.

retrieving the data value using a pointer

you can retrieve the data stored at the located referenced by the pointer variable, using the tostring() method. the following example demonstrates this −

using system;

namespace unsafecodeapplication {
   class program {
      public static void main() {
         unsafe {
            int var = 20;
            int* p = &var;
            
            console.writeline("data is: {0} " , var);
            console.writeline("data is: {0} " , p->tostring());
            console.writeline("address is: {0} " , (int)p);
         }
         console.readkey();
      }
   }
}

when the above code was compiled and executed, it produces the following result −

data is: 20
data is: 20
address is: 77128984

passing pointers as parameters to methods

you can pass a pointer variable to a method as parameter. the following example illustrates this −

using system;

namespace unsafecodeapplication {
   class testpointer {
      public unsafe void swap(int* p, int *q) {
         int temp = *p;
         *p = *q;
         *q = temp;
      }
      public unsafe static void main() {
         testpointer p = new testpointer();
         int var1 = 10;
         int var2 = 20;
         int* x = &var1;
         int* y = &var2;
         
         console.writeline("before swap: var1:{0}, var2: {1}", var1, var2);
         p.swap(x, y);

         console.writeline("after swap: var1:{0}, var2: {1}", var1, var2);
         console.readkey();
      }
   }
}

when the above code is compiled and executed, it produces the following result −

before swap: var1: 10, var2: 20
after swap: var1: 20, var2: 10

accessing array elements using a pointer

in c#, an array name and a pointer to a data type same as the array data, are not the same variable type. for example, int *p and int[] p, are not same type. you can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can't increment that.

therefore, if you need to access an array data using a pointer variable, as we traditionally do in c, or c++ ( please check: c pointers), you need to fix the pointer using the fixed keyword.

the following example demonstrates this −

using system;

namespace unsafecodeapplication {
   class testpointer {
      public unsafe static void main() {
         int[]  list = {10, 100, 200};
         fixed(int *ptr = list)
         
         /* let us have array address in pointer */
         for ( int i = 0; i < 3; i++) {
            console.writeline("address of list[{0}]={1}",i,(int)(ptr + i));
            console.writeline("value of list[{0}]={1}", i, *(ptr + i));
         }
         
         console.readkey();
      }
   }
}

when the above code was compiled and executed, it produces the following result −

address of list[0] = 31627168
value of list[0] = 10
address of list[1] = 31627172
value of list[1] = 100
address of list[2] = 31627176
value of list[2] = 200

compiling unsafe code

for compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler.

for example, to compile a program named prog1.cs containing unsafe code, from command line, give the command −

csc /unsafe prog1.cs

if you are using visual studio ide then you need to enable use of unsafe code in the project properties.

to do this −

  • open project properties by double clicking the properties node in the solution explorer.

  • click on the build tab.

  • select the option "allow unsafe code".