C# Methods - Declaring out parameters
The C# out keyword causes arguments to be passed by reference. Any changes made to the argument inside the method will change the parameter itself also. It is like the ref keyword, except that ref requires that the variable be initialized before it is passed. Declaring a method with out arguments is a classic workaround to return multiple values from a method.
Example:
The example below uses out to return three variables with a single method call.
using System; class MyProgram { static void MyMethod(out int a, out int b, out int c) { a = 10; b = 25; c = a + b; } static void Main(string[] args) { int x, y, z; //calling MyMethod MyMethod(out x, out y, out z); Console.WriteLine("After method call, x = {0}", x); Console.WriteLine("After method call, y = {0}", y); Console.WriteLine("After method call, z = {0}", z); } }
The output of the above code will be:
After method call, x = 10 After method call, y = 25 After method call, z = 35
Example:
Consider one more example, a parameter passed as value is added with above example. This example shows how can we pass parameters into a method in a mixed way.
using System; class MyProgram { static void MyMethod(out int a, out int b, out int c, int p) { a = p + 10; b = p + 25; c = p + a + b; } static void Main(string[] args) { int x, y, z; int k = 100; //calling MyMethod MyMethod(out x, out y, out z, k); Console.WriteLine("After method call, x = {0}", x); Console.WriteLine("After method call, y = {0}", y); Console.WriteLine("After method call, z = {0}", z); } }
The output of the above code will be:
After method call, x = 110 After method call, y = 125 After method call, z = 335
❮ C# - Methods