How to pass pointers as parameters to methods in C#?

CsharpProgrammingServer Side Programming

To pass pointers as parameters to methods, refer the below steps −

Firstly, crate a function swap with unsafe modifier.

public unsafe void swap(int* p, int *q) {
   int temp = *p;
   *p = *q;
   *q = temp;
}

Now under static void main, add the value for the first and second variable, set pointers for both of them.

Display the values of the variables and then call the swap() method shown above. The method swaps the values and displays the result −

public unsafe static void Main() {
   Program p = new Program();
   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();
}
raja
Published on 09-Aug-2018 08:38:33
Advertisements