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


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();
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements