Pass Int by Reference in C#
This post will discuss how to pass an integer by reference in C#.
The method arguments are passed by value by default in C#. To pass an argument by reference in C#, you can make use of the ref parameters. To use ref parameters, both the method definition and the calling method must explicitly use the ref keyword, which indicates that an argument is passed by reference and not by value. The following example passes an integer as a ref parameter and increments its value.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { public static void PassByRef(ref int i) { i++; } public static void Main() { int i = 0; PassByRef(ref i); Console.WriteLine("Value of i is " + i); } } |
Note that the argument that is passed to a ref parameter must be initialized before it is passed. You can even use multiple ref keywords in a method’s parameter list. The following code, for example, swaps two integer values using the ref parameter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Swap(ref int a, ref int b) { int temp = a; a = b; b = temp; } public static void Main() { int a = 1, b = 2; Swap(ref a, ref b); Console.WriteLine("a={0}, b={1}", a, b); // a=2, b=1 } } |
That’s all about passing an integer by reference in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)