Home  >  Article  >  Backend Development  >  How to pass pointer as parameter to method in C#?

How to pass pointer as parameter to method in C#?

WBOY
WBOYforward
2023-08-26 22:13:181245browse

如何将指针作为参数传递给 C# 中的方法?

To pass a pointer as a parameter to a method, see the following steps -

First, create a function exchange using the unsafe modifier.

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

Now under static void main, add the values ​​of the first and second variables, setting pointers for them.

Display the value of the variable and then call the swap() method shown above. This method exchanges 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();
}

The above is the detailed content of How to pass pointer as parameter to method in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete