Unsafe Codes in C#
Mar 27, 2019 02:00 0 Comments C# (C-Sharp) SOUNDARYA

                                                      Unsafe Codes in C#

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 in unsafe mode, please set compilation option in Project >> Compile Options >> Compilation Command to

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

 Pointers

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 was 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 {

&nbs

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect