In C#, the out variable can be used like a reference variable. We don’t need to initialize the variable before passing it into a function call as a out-type. Using out is recommended if you want the function to return multiple modified values.
Let’s see a simple example which is using out variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; public class Program { // User defined function public void Show(out int val) // Out parameter { int square = 5; val = square; val *= val; // Manipulating value } // Main function, execution entry point of the program public static void Main(string[] args) { int val = 50; Program program = new Program(); // Creating Object Console.WriteLine("Value before passing out variable " + val); program.Show(out val); // Passing out argument Console.WriteLine("Value after recieving the out variable " + val); } } |
Output
1 2 3 4 |
Value before passing out variable 50 Value after recieving the out variable 25 |