Home > Backend Development > C#.Net Tutorial > How to pass pointer as parameter to method in C#?

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

WBOY
Release: 2023-08-26 22:13:18
forward
1326 people have browsed it

如何将指针作为参数传递给 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;
}
Copy after login

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template