In C#, an out
parameter is used to pass a value from a method back to the calling code. It is similar to the ref
parameter, but with a slight difference: an out
parameter does not require the variable to be initialized before passing it to the method. This allows the method to assign a value to the parameter.
Here’s an example of how to use an out
parameter in C#:
public class Program { static void Main() { int result; bool success = Divide(10, 3, out result); if (success) { Console.WriteLine("The division result is: " + result); } else { Console.WriteLine("Division failed."); } } static bool Divide(int dividend, int divisor, out int quotient) { if (divisor != 0) { quotient = dividend / divisor; return true; } else { quotient = 0; return false; } } }
In this example, the Divide
method takes two integers as input (dividend
and divisor
) and calculates the quotient. The out
parameter quotient
is used to return the result back to the calling code.
In the Main
method, we declare an int
variable result
and pass it as an out
parameter to the Divide
method. If the division is successful (i.e., the divisor is not zero), the Divide
method assigns the result to the quotient
parameter and returns true
. In the calling code, we check the value of the success
variable to determine whether the division was successful, and if so, we display the result.
Note that when using an out
parameter, you must assign a value to it inside the method before returning. Otherwise, you’ll get a compilation error.