Use of unsafe keyword in C#

Posted by Abhisek under C# category on | Views : 3413
Unsafe keyword

In C# the value can be directly referenced to a variable, so there is no need of pointer. Use of pointer sometime crashes the application. But C# supports pointer, that means we can use pointer in C#.

The use of pointer in C# is defined as a unsafe code . So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration. But pointer does not come under garbage collection.

int a, *b;
a = 25;
b = &a;
Console.WriteLine("b= {0}",b);//returns b= 25

See the below program for swapping of two numbers using pointer in C#.
 class Swapping
//declaring pointers inside unsafe code
unsafe public static void UnsafeSwap(int* i, int* j)
int temp = *i;
*i = *j;
*j = temp;

static void Main(string args[])
// Values for swapping.

int i = 10, j = 20;
// Swap values using pointer
Console.WriteLine("Values before swap: i = {0}, j = {1}", i, j);
unsafe //passing the values to unsafe code
UnsafeSwap(&i, &j);
Console.WriteLine("Values after swap: i = {0}, j = {1}", i, j);

Values before swap: i = 10, j = 20
Values after swap: i = 20, j = 10

Comments or Responses

Login to post response