C# functions with out variable

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.

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
Value before passing out variable 50
Value after recieving the out variable 25



ADVERTISEMENT
ADVERTISEMENT